Java Reference
In-Depth Information
Heavyweight components are more complex than lightweight components in
general. A frame, for example, has multiple panes, which are responsible for vari-
ous characteristics of the frame window. All visible elements of a Java interface
are displayed in a frame's content pane .
Generally, we can create a Java GUI-based application by creating a frame in
which the program interface is displayed. The interface is often organized onto a
primary panel, which is added to the frame's content pane. The components in the
primary panel are often organized using other panels as needed.
Containers are generally not useful unless they help us organize and display
other components. Let's examine another fundamental GUI component. A label
is a component that displays a line of text in a GUI. A label can also display an
image, a topic discussed later in this chapter. Usually, labels are used to display
information or identify other components in the GUI. Labels can be found in
almost every GUI-based program.
Let's look at an example that uses frames, panels, and labels. When the pro-
gram in Listing 3.7 is executed, a new window appears on the screen displaying
a phrase. The text of the phrase is displayed using two label components. The
labels are organized in a panel, and the panel is displayed in the content pane of
the frame.
The JFrame constructor takes a string as a parameter, which it displays in the
title bar of the frame. The call to the setDefaultCloseOperation method deter-
mines what will happen when the close button (the X ) in the corner of the frame
is clicked. In most cases we'll simply let that button terminate the program, as
indicated by the EXIT_ON_CLOSE constant.
A panel is created by instantiating the JPanel class. The background color of
the panel is set using the setBackground method. The setPreferredSize method
accepts a Dimension object as a parameter, which is used to indicate the width
and height of the component in pixels. The size of many components can be set
this way, and most also have setMinimumSize and setMaximumSize methods to
help control the look of the interface.
The labels are created by instantiating the JLabel class, passing to its con-
structor the text of the label. In this program two separate label components are
created.
Containers have an add method that allows other components to be added
to them. Both labels are added to the primary panel and are from that point on
considered to be part of that panel. The order in which components are added to
a container often matters. In this case, it determines which label appears above
the other.
Finally, the content pane of the frame is obtained using the getContentPane
method, immediately after which the add method of the content pane is called to
 
Search WWH ::




Custom Search