Java Reference
In-Depth Information
GridBagLayout Lays out different size components within a flexible grid.
BoxLayout
Lays out components vertically or horizontally within a box.
SpringLayout
Lays out components subject to a set of constraints.
Frankly, the topic of layout managers is quite large, and it is not possible to examine it in
detail in this topic. Fortunately, this chapter uses only two layout managers— BorderLay-
out and FlowLayout —and both are very easy to use.
BorderLayout is the default layout manager for the content pane. It implements a layout
style that defines five locations to which a component can be added. The first is the center.
The other four are the sides (i.e., borders), which are called north, south, east, and west. By
default, when you add a component to the content pane, you are adding the component to
the center. To add a component to one of the other regions, specify its name.
Although a border layout is useful in some situations, often another, more flexible layout
manager is needed. One of the simplest is FlowLayout . A flow layout lays out components
one row at a time, top to bottom. When one row is full, layout advances to the next row.
Although this scheme gives you little control over the placement of components, it is quite
simple to use. However, be aware that if you resize the frame, the position of the compon-
ents will change.
A First Simple Swing Program
Swing programs differ from the console-based programs shown earlier in this topic. They
also differ from the AWT-based applets shown in Chapter 15 . Not only do Swing programs
use the Swing component set to handle user interaction, but they also have special require-
ments that relate to threading. The best way to understand the structure of a Swing program
is to work through an example. There are two types of Java programs in which Swing is
typically used. The first is a desktop application. The second is the applet. This section
shows how to create a Swing application. The creation of a Swing applet is described later
in this chapter.
Although quite short, the following program shows one way to write a Swing applica-
tion. In the process it demonstrates several key features of Swing. It uses two Swing com-
ponents: JFrame and JLabel . JFrame is the top-level container that is commonly used for
Swing applications. JLabel is the Swing component that creates a label, which is a com-
ponent that displays information. The label is Swing's simplest component because it is
passive. That is, a label does not respond to user input. It just displays output. The program
uses a JFrame container to hold an instance of a JLabel . The label displays a short text
message.
Search WWH ::




Custom Search