5

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Azuu
  • 836
  • 2
  • 16
  • 32
  • 2
    for better help sooner edit your question with a [SSCCE](http://sscce.org/) demonstrated your issue with Image and JPanel – mKorbel May 17 '12 at 11:01
  • can you post the relevant code regarding the image and JPanel? – CosminO May 17 '12 at 11:01
  • I have a class which extends JPanel and using paintComponent i m inserting image on it.. n i m passing image path in constructor. – Azuu May 17 '12 at 11:51
  • 2
    *"I have JPanel Which will load images."* If these are user images, it might be best to put them in a `JLabel` inside a `JScrollPane`. You don't want that 'portrait' style image of your mother stretched all across the view port. ;) – Andrew Thompson May 18 '12 at 07:04

2 Answers2

11

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.

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
COD3BOY
  • 11,964
  • 1
  • 38
  • 56
  • But the problem here is i m not getting jpanels width and height.. I have class which extends JPanel and i m putting image on this panel. when i try to get width and height it shows 0.0 – Azuu May 17 '12 at 11:55
  • 1
    @Azuu : Then override it's `getPreferredSize()` as you doing with `paintComponent(...)` method and let is return some value e.g. `return new Dimension(500, 500);` , that will do, now you can calculate it's height and width. – nIcE cOw May 17 '12 at 16:45
6

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);
    }
}
Wolf
  • 991
  • 1
  • 9
  • 12
  • 1
    This, for me at least, was more practical than the above. I actually had the same class written, but I didn't have the width and height arguments. Thank you. – Andrew No Sep 16 '15 at 01:31
  • This does work, but obviously breaks image scale. So for images where width and height are not equal this will introduce warping. – Koenigsberg Oct 06 '21 at 09:20