Search code examples
javaimageswingresizejlabel

How to resize an image in a JLabel as the window resizes? How to maintain proper scale?


Say I've got an image in a JLabel. Here's how I'm currently adding it:

p=resizeImage(p,lbl.getWidth(),lbl.getHeight());
lbl.setIcon(p);

I'd like to resize this as the label is resized.

  • How can I accomplish this?
  • how can I resize while maintaining proportion?

I could write a small function to get the image width to height ratio, get the label width and height, find the smaller of the two(proportionally) and calculate the new height and width manually. That would not be an issue, but I wonder if there's a cleaner way.


Solution

  • You could listen to resize-events of the label or, what I would prefer, paint the image directly (replacing the JLabel with JComponent).