Icons

Swing introduces the concept of an icon for use in a variety of components. The Icon interface and ImageIcon class make dealing with simple images extremely easy.

The Icon interface is very simple, specifying just three methods used to determine the size of the Icon and display it. Implementations of this interface are free to store and display the image in any way, providing a great deal of flexibility. In other words, icons don’t have to be bitmaps or GIF images, but are free to render themselves any way they choose. As we’ll see later, an icon can simply draw on the component if that’s more efficient. The examples at the end of this section show a couple of different ways the interface might be implemented.

Properties

The Icon interface defines the properties listed in Table 4-3. The iconHeight and iconWidth properties specify the size of the Icon in pixels.

Table 4-3. Icon properties

Property

Data type

get

is

set

Default value

iconHeight

int

·

   

iconWidth

int

·

   

Method

public void paintIcon(Component c, Graphics g, int x, int y)

Paint the Icon at the specified location on the given Graphics. For efficiency reasons, the Graphics object will (probably) not be clipped, so be sure not to draw “outside the lines.” You must make sure to keep your horizontal position between x and x + getIconWidth( ) - 1, and your vertical position between y and y + getIconHeight( ) - 1 while painting. The Component is provided to allow its properties (such as foreground or background color) to be used when painting or so it can be used as an image observer (see Section 4.7 later in this chapter).

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.