user1715408
user1715408

Reputation:

How to fit Image size to JFrame Size?

I have a JPanel into a JFrame. I loaded a picture on the JPanel but its shown just a part of the picture: This is the part of the code where i did it:

JPanel panelImg = new JPanel()
{
    public void paintComponent(Graphics g)
    {
        Image img = new ImageIcon("Welcome.png").getImage();
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
        g.drawImage(img, 0, 0, null);
    }
};
mainFrame.add(panelImg);

So this is how it looks like:

Picture 1

The complete picture looks like this:

enter image description here

Is there a way to scale the picture to the JFrames size? Thanks in advance

Upvotes: 11

Views: 66960

Answers (4)

javatar
javatar

Reputation: 1340

Its Easy. Follow this example,

public class BasePanel extends JPanel {

ImageIcon backImage;
public BasePanel() {
    backImage = new ImageIcon("src/images/welcome.png");
}

@Override
protected void paintComponent(Graphics g) {
    BufferedImage scaledImage = getScaledImage();
    super.paintComponent(g);
    g.drawImage(scaledImage, 0, 0, null);
}

private BufferedImage getScaledImage(){
    BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) image.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
    g2d.drawImage(backImage.getImage(), 0, 0,getWidth(),getHeight(), null);

    return image;
}

}

Upvotes: 1

trashgod
trashgod

Reputation: 205785

You want the drawImage() that scales to the target container. See the article cited here for alternatives. For example,

g.drawImage(img, 0, 0, getWidth(), getHeight(), this);

Upvotes: 14

AvB
AvB

Reputation: 171

you can try this :

Image img = new ImageIcon(ImageIO.read(new File("welcome.png"))
                               .getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH)));

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

First of all, I wouldn't be loading the image inside the paintComponent method, this method is call repeatedly (and some times in quick succession), you don't want to do anything that takes time to execute or consumes resources unnecessarily

Check out Java: maintaining aspect ratio of JPanel background image for suggestions on filling/fitting images to a given area

Upvotes: 13

Related Questions