Java Tips Weblog

  • Blog Stats

    • 1,761,518 hits
  • Categories

  • Archives

Thumbnail Icon

Posted by Darryl Burke on April 14, 2012

In the last two posts, we presented StretchIcon and ShrinkIcon, both used for scaling images to fit a component whose size is determined by the size and layout of its container.  ThumbnailIcon extends ShrinkIcon to reduce an image when needed to fit within a defined size, padding and centering it horizontally or vertically as required.  Like ShrinkIcon, this class does not magnify the image.

As its name implies, ThumbnailIcon is useful for displaying multiple images of different sizes, reduced and/or padded as necessary to fit the same dimensions.  These dimensions will usually be the default dimensions for the class, but can be set for individual icons.  The initial default size for ThumbnailIcons is 160 X 120 pixels, which can be changed via the static method setDefaultSize(int width, int height).  Since an Icon is a shared resource that does not retain a reference to any component(s) to which the Icon may be set, code that changes the size of an already displayed ThumbnailIcon is responsible for repainting the component(s) affected by the change.

A newly constructed ThumbnailIcon will use the default dimensions; to set a non-default size for an individual ThumbnailIcon use setThumbWidth(int width) and/or setThumbHeight(int height). Setting the thumb width or height (or the default width or height) to COMPUTED or 0 will make the icon use the aspect ratio of the contained image to compute that dimension from the other.  To revert to using the default width/height, set the thumb width/height to DEFAULT.

If both the width and height evaluate to COMPUTED / 0, a ThumbnailIcon will adopt the natural size of its contained image, which is essentially the same behavior as ImageIcon.

A convenience method has been added to obtain the thumbnail as a BufferedImage the size of the actually displayed image.  Note that a thumbnail obtained from an animated image will not itself be animated.

Like StretchIcon and ShrinkIcon, ThumbnailIcon is a drop-in replacement for ImageIcon, except that, once again, ImageIcon’s no-arg constructor isn’t supported.  Unlike the former two, its size is not determined by the component in which it is shown.

Get The Code

See Also

Stretch Icon
Shrink Icon

Related Reading

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

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: