ptg7068951
174 HOUR 13:Building a Simple User Interface
The only thing that SalutonFramedisplays is a title—the Esperanto greeting
“Saluton mondo!” The frame is an empty window because it doesn’t contain
any other components yet.
To add components to a frame, you must create the component and add it to
the container. Each container has an add()method that takes one argument:
the component to display.
The SalutonFrameclass includes a setLookAndFeel()method that desig-
nates Nimbus as the frame’s look and feel. The setLookAndFeel()method
of the UIManagerclass is called in lines 14–16 to accomplish this.
The call to this method is placed inside a try-catchblock, which enables
errors that might occur to be handled. The tryand catchstatements are
new because they haven’t been introduced yet. Dealing with errors using
these statements is covered in Hour 18, “Handling Errors in a Program.”
At this point, all you need to know is that calling UIManager.setLookAndFeel()
sets a GUI’s look and feel. Any error that might occur as a result will just cause
a program to keep the default look and feel instead of Nimbus.
Buttons
Onesimple component you can add to a container is a JButtonobject.
JButton, like the other components you are working with during this hour,
is part of the java.awt.swingpackage. AJButtonobject is a clickable button
with a label that describes what clicking the button does. This label can be
text, graphics, or both. The following statement creates a JButtoncalled
okButtonand gives it the text label OK:
JButton okButton = new JButton(“OK”);
After a component such as JButtonis created, it should be added to a con-
tainer by calling its add()method:
add(okButton);
FIGURE 13.1
Displaying a frame in an
application.