0

Just like we can resize a JFrame I'd like to show an image on a frame. I'd like to be it resizeable so when I resize the image should be resized.

How could I do this?

try {
    myPicture = ImageIO.read(f);
    picLabel.setIcon(new ImageIcon(myPicture));
    panel.add(picLabel);
} catch (IOException e) {
    e.printStackTrace();
}

I added the label (with the image) to a JPanel and the panel is added to the frame.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
fucorogu
  • 43
  • 6
  • 2
    [Custom painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/) the image seems the best approach for something like this. Forget the `ImageIcon` and `JLabel` - instead paint the image directly in a `JPanel` & adjust the size & position as needed when painting it to the graphics. – Andrew Thompson Aug 06 '17 at 11:52

2 Answers2

0

ImageIcons are always resizeable. Try converting it to an image, resizing it, convert it back to an ImageIcon, and then reapplying it (of course do this when you want to resize it).

Image myScaledPicture = myPicture.getImage().getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
picLabel.setIcon(new ImageIcon(myScaledPicture);

More info here: How to resize JLabel ImageIcon?

camo5hark
  • 214
  • 1
  • 5
0

You can use the Stretch Icon.

It can be used in any component that can paint an Icon and the image will scale as the component is resized.

It is reusable code so you don't have to do custom painting all the time.

camickr
  • 321,443
  • 19
  • 166
  • 288