Working with Images
JLabels make it very
simple to add graphics to your user interface. Images used in JLabels (and also in other Swing components,
such as buttons) are of type javax.swing.Icon, an interface described in
detail in the next section.
These two lines of code show how simple it is to create a label containing an image:
ImageIcon icon = new ImageIcon("images/smile.gif");
JLabel label = new JLabel(icon);For labels that contain both graphics and text, Swing provides
considerable flexibility with respect to the relative location of the
text and image. The text for the label may be displayed at any one of
nine locations relative to the image. These locations are specified via
the setVerticalTextPosition( ) and
setHorizontalTextPosition( ) methods,
which take values from the SwingConstants class discussed earlier. Note
the distinction between the label’s text position and its alignment;
text position reflects the position of the text relative to the image
while alignment specifies the location of the label’s contents (image
and text) relative to the borders of the label.
Another useful feature of the JLabel class is the ability to enable and
disable the label by “graying out” the label and text. By default, a
call to JLabel.setEnabled(false)
switches the image to an automatically generated grayscale version of
the original image and alters the text rendering in some
(L&F-specific) way. However, the grayscale image is used only if no
disabled icon has been set. The setDisabledIcon( ...