Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image resize to fit on JPanel

I have JPanel Which will load images.

Since images will not have the same width and height as the JPanel, I want to make the image resize and fit in the JPanel.

like image 404
Azuu Avatar asked May 17 '12 10:05

Azuu


2 Answers

Read on this article, The Perils of Image.getScaledInstance()

Now IF you STILL prefer you can use something like,

Image scaledImage = originalImage.getScaledInstance(jPanel.getWidth(),jPanel.getHeight(),Image.SCALE_SMOOTH);

this before loading the image to your JPanel, probably like discussed in this answer.

like image 189
COD3BOY Avatar answered Sep 23 '22 00:09

COD3BOY


I know this is quite old, but maybe this helps other people

use this class instead of a normal JLabel and pass an ImageIcon when using setIcon(#);

private class ImageLabel extends JLabel{
    private Image _myimage;

    public ImageLabel(String text){
        super(text);
    }

    public void setIcon(Icon icon) {
        super.setIcon(icon);
        if (icon instanceof ImageIcon)
        {
            _myimage = ((ImageIcon) icon).getImage();
        }
    }

    @Override
    public void paint(Graphics g){
        g.drawImage(_myimage, 0, 0, this.getWidth(), this.getHeight(), null);
    }
}
like image 28
Wolf Avatar answered Sep 22 '22 00:09

Wolf