Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

176 HOUR 13:Building a Simple User Interface


24: “com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”
25: );
26: } catch(Exception exc) {
27: // ignore error
28: }
29: }
30:
31: public static voidmain(String[] arguments) {
32: Playback pb = new Playback();
33: }
34: }

The Playback program creates a FlowLayoutlayout manager in line 10 and
sets the frame to employ it in line 11. When three buttons are added to the
frame in lines 15–17, they’re arranged by this manager.
When you run the application, your output should resemble Figure 13.2.
You can click each of the buttons, but nothing happens in response because
your program does not contain any methods to receive user input—that’s
covered during Hour 15.
You can add many Swing user components to a container in this manner.

Labels and Text Fields
AJLabelcomponent displays information that the user cannot modify.
This information can be text, a graphic, or both. These components are
often used to label other components in an interface, hence the name. They
often identify text fields.
AJTextFieldcomponent is an area where a user can enter a single line of
text. You can set up the width of the box when you create the text field.
The following statements create a JLabelcomponent and JTextField
object and add them to a container:
JLabel pageLabel = new JLabel(“Web page address: “, JLabel.RIGHT);
JTextField pageAddress = new JTextField(20);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(pageLabel);
add(pageAddress);

Figure 13.3 shows this label and text field side-by-side. Both of the state-
ments in this example use an argument to configure how the component
should look.

LISTING 13.2 Continued

FIGURE 13.2
Displaying buttons on a GUI.


NOTE
Because so many different user
interface components must be
introduced during this hour,the
full source code used to create
each figure is not listed here.
Yo u c a n f i n d f u l l v e r s i o n s o f
each program on the book’s
website at http://www.java24hours.
com on the Hour 13 page.

Free download pdf