Java Tips Weblog

  • Blog Stats

    • 1,761,065 hits
  • Categories

  • Archives

Shrink Icon

Posted by Darryl Burke on April 8, 2012

When writing about StretchIcon, published earlier, I mentioned that the image chosen for a StretchIcon should be large enough that it does not get magnified in fitting it to the component, since drawing an image larger than its natural size can lead to pixelation.  ShrinkIcon extends StretchIcon to ensure such pixelation doesn’t happen.

Like StretchIcon, ShrinkIcon is meant to be used only in conjunction with a component whose size is determined by the size and layout of the container in which it is placed.  The image will be reduced if necessary to fit within the bounds of the component; it will not, however, be drawn at larger than its natural size.

In the event that the component is wider and/or taller than the image, ShrinkIcon will pad and center the image horizontally and/or vertically.  Only when the component is too small to accommodate the image at its natural size will the image be scaled on one or both axes to fit, optionally maintaining the aspect ratio of the image.  This can make it a better choice than StretchIcon for displaying images of varied sizes in components that are all the same size; for example, JLabels in a GridLayout.  While large images will be reduced to fit, smaller images aren’t at the risk of being blown up and pixelated beyond recognition.

Like StretchIcon, ShrinkIcon is a drop-in replacement for ImageIcon, except, again, that ImageIcon’s no-arg constructor isn’t supported.

Get The Code

See Also

Stretch Icon
Thumbnail Icon

Related Reading

Java API: javax.swing.Icon
Java API: javax.swing.ImageIcon
The Java™ Tutorials: How to Use Icons

2 Responses to “Shrink Icon”

  1. Anonymous said

    Thank you for sharing your code. I gave it a try and it works as expected except for one exception. After minimizing and then maximizing my JFrame, my ShrinkIcon disappears. Is there a way around this? I have tried addWindowStateListener … windowStateChanged … paintIcon but no effect.

    • The problem isn’t with ShrinkIcon. It may have to do with the way you are using the class, so I suggest you find an active Java forum and ask for advice there.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: