Is there any property or any code that I can implement to make an icon inside a JLabel
resizable. Or is there any other item which can store an image, that I could use to have a resizable image inside a JFrame
?

- 14,363
- 4
- 24
- 53

- 13
- 3
-
What you mean by resizable? if you resize your jlabel then the icon could resize too – nachokk Feb 25 '14 at 21:55
-
I'm using netbeans, and when I try to resize the jlabel i cant, the size of the image inside just stays fixed while the jlabel is being resized (which cuts parts of the image). – user2388072 Feb 25 '14 at 22:00
-
Short answer: You will have to make something yourself or find a library that does it for you. Take a look here: http://stackoverflow.com/questions/14548808/scale-the-imageicon-automatically-to-label-size – sorifiend Feb 25 '14 at 22:06
3 Answers
use this code :
photo = new ImageIcon(UrlofPhoto);
Image im = photo.getImage();
Image Newim = im.getScaledInstance(yourlabel.getWidth(), yourlabel.getHeight(),Image.SCALE_SMOOTH);
ImageIcon Newphoto=new ImageIcon(Newim);
yourlabel.setIcon(Newphoto);
don't forget to set an initialised size to yourlabel

- 77
- 7
-
Take a look at [The Perils of Image.getScaledInstance()](http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html) for reasons why this is not always a good idea... – MadProgrammer Feb 25 '14 at 23:37
Generally, I would't suggest trying this with a JLabel
as JLabel
has a lot of other features you really don't want to messing with (alignment and text).
Generally, a better solution is to use a dedicated "image" panel, which you can provide additional control over to fine tune how you want the scaling to work.
For example
If you're really stuck on using JLabel
, I would recommend attaching a ComponentListener
to it and resizing the underlying image when ever it changes size. The problem with this is componentResized
may be called repeatedly in quick succession, meaning you will need to devise some kind of coalescing algorithm that only reacts to the last event within a given period of time...

- 1
- 1

- 343,457
- 22
- 230
- 366
Check out Darryl's Stretch Icon which will dynamically scale the icon to fill the label.

- 321,443
- 19
- 166
- 288