Image Resizing for JPanel

I have a JPanel that will upload images.

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

+3
source share
2 answers

Read this article, The Dangers of Image.getScaledInstance ()

Now IF you prefer STILL , you can use something like

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

before uploading the image to your JPanel, possibly as discussed in this answer .

+10
source

I know this is pretty old, but maybe it helps other people.

JLabel ImageIcon 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);
    }
}
+3

All Articles