Java Reference
In-Depth Information
SR 3.43 In the NestedPanels program, which panels are added to another
panel? Which panel are they added to? Which panel is explicitly added
to the content pane of the frame?
3.11 Images
Images often play an important role in graphics-based software. Java has the abil-
ity to use JPEG and GIF images in various ways. The Graphics class contains a
drawImage method that allows you to draw the image just as you would draw a
shape or character string. An image can also be incorporated into a label com-
ponent. Let's explore the relationship between images and labels in more detail.
As we've seen in previous sections, a label defined by the
JLabel class can be used to provide information to the user
or to describe other components in an interface. A JLabel
can also contain an image. That is, a label can be composed
of text, an image, or both.
The ImageIcon class is used to represent an image that is included in a label.
The ImageIcon constructor takes the name of the image file and loads it into the
object. ImageIcon objects can be made using either JPEG or GIF images.
The alignment of the text and image within the label can be set explicitly, using
either the JLabel constructor or specific methods. Similarly, we can set the posi-
tion of the text relative to the image.
The LabelDemo program shown in Listing 3.9 displays several labels. Each label
shows its text and image in different orientations.
The third parameter passed to the JLabel constructor defines the horizontal
positioning of the label within the space allowed for the label in the panel. The
SwingConstants interface contains several constants used by various Swing com-
ponents, making it easier to refer to them.
The orientation of the label's text and image is explicitly set using the
setHorizontalTextPosition and setVerticalTextPosition methods. As
shown in the case of the first label, the default horizontal position for text is on
the right (image on the left), and the default vertical position for text is centered
relative to the image.
Don't confuse the horizontal positioning of the label in the container with the set-
ting of the orientation between the text and the image. The third parameter of the
constructor determines the first, and the explicit method calls determine the second.
By putting an image in a label, it becomes part of a component that gets laid
out with all other components in a container, instead of being drawn in a particu-
lar place. This is an appropriate design decision: whether to draw an image using
KEY CONCEPT
A label can contain text, an image,
or both.
 
Search WWH ::




Custom Search