简体   繁体   中英

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM