Java Reference
In-Depth Information
There are four basic steps to creating a GUI in Java:
1.
Create and conÞgure the components
You create a GUI component just like any other object in Java, by calling the
constructor. You'll need to consult the documentation for individual compo-
nents to determine what arguments a constructor expects. For example, to
create a Swing JButton component that displays the label “Quit”, simply
write:
JButton quit = new JButton("Quit");
Once you have created a component, you may want to configure it by setting
one or more properties. For example, to specify the font a JButton compo-
nent should use, you can write:
quit.setFont(new Font("sansserif", Font.BOLD, 18));
Again, consult the documentation for the component you are using to deter-
mine what methods you can use to configure the component.
2.
Add the components to a container
All components must be placed within a container . Containers in Java are all
subclasses of java.awt.Container . Commonly used containers include JFrame
and JDialog classes, which represent top-level windows and dialog boxes,
respectively. The java.applet.Applet class, which is subclassed to create
applets, is also a container and can therefore contain and display GUI compo-
nents. A container is a type of component, so containers can be, and com-
monly are, nested within other containers. JPanel is a container that is often
used in this manner. In developing a GUI, you are really creating a contain-
ment hierarchy: the top-level window or applet contains containers that may
contain other containers, which in turn contain components. To add a compo-
nent to a container, you simply pass the component to the add() method of
the container. For example, you can add a quit button to a “button box” con-
tainer with code like the following:
buttonbox.add(quit);
3.
Arrange, or lay out, the components
In addition to specifying which components are placed inside of which con-
tainers, you must also specify the position and size of each component within
its container, so that the GUI has a pleasing appearance. While it is possible
to hardcode the position and size of each component, it is more common to
use a LayoutManager object to lay out the components of a container automat-
ically according to certain layout rules defined by the particular LayoutMan-
ager you have chosen. We'll learn more about layout management later in
this chapter.
4.
Handle the events generated by the components
The steps described so far are sufficient to create a GUI that looks good on
the screen, but our graphical “user interface” is not complete, because it does
not yet respond to the user. As the user interacts with the components that
Search WWH ::




Custom Search