How to fit Image size to JFrame Size?

user1715408 picture user1715408 · Oct 23, 2012 · Viewed 57k times · Source

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

Answer

trashgod picture trashgod · Oct 23, 2012

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);