Sams Teach Yourself Java 2 in 24 Hours
- Table of Contents
- Copyright
- About the Author
- About the Technical Editor
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Hour 1. Becoming a Programmer
- Hour 2. Writing Your First Program
- Hour 3. Vacationing in Java
- Hour 4. Understanding How Java Programs Work
- Part II: Learning the Basics of Programming
- Hour 5. Storing and Changing Information in a Program
- Hour 6. Using Strings to Communicate
- Hour 7. Using Conditional Tests to Make Decisions
- Hour 8. Repeating an Action with Loops
- Part III: Working with Information in New Ways
- Hour 9. Storing Information with Arrays
- Hour 10. Creating Your First Object
- Hour 11. Describing What Your Object Is Like
- Hour 12. Making the Most of Existing Objects
- Part IV: Programming a Graphical User Interface
- Hour 13. Building a Simple User Interface
- Hour 14. Laying Out a User Interface
- Hour 15. Responding to User Input
- Hour 16. Building a Complex User Interface
- Part V: Creating Multimedia Programs
- Hour 17. Creating Interactive Web Programs
- Hour 18. Handling Errors in a Program
- Hour 19. Creating a Threaded Program
- Hour 20. Reading and Writing Files
- Part VI: Creating Multimedia Programs
- Hour 21. Using Fonts and Color
- Hour 22. Playing Sound Files
- Hour 23. Working with Graphics
- Hour 24. Creating Animation
- Part VII: Appendixes
- Appendix A. Tackling New Features of Java 2 Version 1.4
- Appendix B. Using the Java 2 Software Development Kit
- Appendix C. Programming with the Java 2 Software Development Kit
- Appendix D. Using Sun ONE Studio
- Appendix E. Where to Go from Here: Java Resources
- Appendix F. This Book's Web Site
Using Components
In Java, every part of a graphical user interface is represented by a class in the Swing or Abstract Windowing Toolkit packages. There is a JButton class for buttons, a JWindow class for windows, a JTextField class for text fields, and so on.
To create and display an interface, you create objects, set their variables, and call their methods. The techniques are the same as those you used during the previous three hours as you were introduced to object-oriented programming.
When you are putting a graphical user interface together, you work with two kinds of objects: components and containers. A component is an individual element in a user interface, such as a button or slider. A container is a component that can be used to hold other components.
The first step in creating an interface is to create a container that can hold components. In an application, this container is often a frame or a window. You will use another, the applet window, in Hour 17, "Creating Interactive Web Programs."
Frames and Windows
Windows and frames are containers that can be displayed on a user's desktop. Windows are simple containers that do not have a title bar or any of the other buttons normally along the top edge of a graphical user interface. Frames are windows that include all of these common windowing features users expect to find when they run software—such as buttons to close, expand, and shrink the window.
These containers are created using Swing's JWindow and JFrame classes. To make the Swing package of classes available in a Java program, use the following statement:
import javax.swing.*;
One way to make use of a frame in a Java application is to make the application a subclass of JFrame. Your program will inherit the behavior it needs to function as a frame. The following statements create a subclass of JFrame:
import javax.swing.*;
public class MainFrame extends JFrame {
public MainFrame() {
// set up the frame
}
}
This class creates a frame, but doesn't set it up completely. In the frame's constructor method, you must do several actions when creating a frame:
- Call a constructor method of the superclass, JFrame.
- Set up the title of the frame.
- Set up the size of the frame.
- Define what happens when the frame is closed by a user.
You also must make the frame visible, unless for some reason it should not be displayed when the application begins running.
All of these things can be handled in the frame's constructor method. The first thing the method must contain is a call to one of the constructor methods of JFrame, using the super statement. Here's an example:
super();
The preceding statement calls the JFrame constructor with no arguments. You can also call it with the title of your frame as an argument:
super("Main Frame");
This sets the title of the frame, which appears in the title bar along the top edge, to the specified string. In this example, the text greeting "Main Frame" will appear.
If you don't set up a title in this way, you can call the frame's setTitle() method with a String as an argument:
setTitle("Main Frame");
The size of the frame can be established by calling its setSize() method with two arguments: the width and height. The following statement sets up a frame that is 350 pixels wide and 125 pixels tall:
setSize(350, 125);
Another way to set the size of a frame is to fill it with components and then call the frame's pack() method with no arguments, as in this example:
pack();
The pack() method sets the frame up based on the preferred size of each component inside the frame. Every interface component has a preferred size, though this is sometimes disregarded depending on how components have been arranged within a container. You don't need to explicitly set the size of a frame before calling pack()—the method sets it to an adequate size before the frame is displayed.
Every frame is displayed with a button along the title bar that can be used to close the frame. On a Windows system, this button appears as an X in the upper-right corner of the frame. To define what happens when this button is clicked, call the frame's setDefaultCloseOperation() method with one of four JFrame class variables as an argument:
- • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)— Exit the program when the button is clicked.
- setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)— Close the frame, dispose of the frame object, and keep running the application.
- setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)— Keep the frame open and continue running.
- setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)— Close the frame and continue running.
The last thing that's required is to make the frame visible: call its setVisible() method with true as an argument:
setVisible(true);
This opens the frame at the defined width and height. You can also call it with false to stop displaying a frame.
Listing 13.1 contains the source code described in this section. Enter these statements and save the file as SalutonFrame.java.
Example 13.1. The Full Text of SalutonFrame.java
1: import javax.swing.*;
2:
3: public class SalutonFrame extends JFrame {
4: public SalutonFrame() {
5: super("Saluton mondo!");
6: setSize(350, 100);
7: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8: setVisible(true);
9: }
10:
11: public static void main(String[] arguments) {
12: SalutonFrame sal = new SalutonFrame();
13: }
14: }
Lines 11–13 of Listing 13.1 contain a main() method, which turns this frame class into an application that can be run at the command line. After you compiling this into a class, run the application with the following command:
java SalutonFrame
Figure 13.1 shows the result. The only thing that SalutonFrame displays is a title—the Esperanto greeting "Saluton mondo!" The frame is an empty window, because it doesn't contain any other components yet.
Figure 13.1 Displaying a frame in an application.
To add components to a frame, window, or an applet, you must work with the content pane of these containers. A content pane is the area in a container that can hold other components. They are represented in Java by the Container class, which is part of the Abstract Windowing Toolkit. To make the toolkit available in your Java classes, use the following import statement:
import java.awt.*;
Using a content pane requires three steps:
- Create a pane by calling a container's getContentPane() method, which produces a Container object that represents the pane.
- Create components and add them to the pane by calling the pane's add() method.
- Call setContentPane() with your pane as an argument.
You will work with content panes in the next section.
Buttons
One simple component you can add to a container is a JButton object. JButton, like the other components you'll be working with during this hour, is part of the java.awt.swing package. A JButton object is a clickable button with a label that describes what clicking the button will do. This label can be text, graphics, or both. The following statement creates a JButton called okButton and gives it the text label OK:
JButton okButton = new JButton("OK");
After a component such as JButton is created, it should be added to a container. In a container such as a frame, the following statement creates a Container object called pane and sets it up with the value of the container's content pane:
Container pane = getContentPane();
Because the pane object represents a content pane for a container, components can be added to this object by calling its add() method. The component to add should be the only argument to this method. For example, the previously created okButton object could be added to the pane container with the following statement:
pane.add(okButton);
When you add components to a container, you do not specify the place in the container where the component should be displayed. The arrangement of components is decided by an object called a layout manager. The simplest of these managers is the FlowLayout class, which is part of the java.awt package.
To make a container use a specific layout manager, you must first create an object of that layout manager's class. A FlowLayout object is created with a statement, such as the following:
FlowLayout fff = new FlowLayout();
Once a layout manager has been created, the container's setLayoutManager () method is called to associate the manager with the container. The only argument to this method should be the layout manager object, as in the following example:
pane.setLayoutManager(fff);
This statement designates the fff object as the layout manager for the pane container.
Listing 13.2 contains a Java application that displays a frame with three buttons.
Example 13.2. The Full Text of Playback.java
1: import javax.swing.*;
2: import java.awt.*;
3:
4: public class Playback extends JFrame {
5: public Playback() {
6: super("Playback");
7: setSize(225, 80);
8: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9: setVisible(true);
10: Container pane = getContentPane();
11: FlowLayout flo = new FlowLayout();
12: pane.setLayout(flo);
13: JButton play = new JButton("Play");
14: JButton stop = new JButton("Stop");
15: JButton pause = new JButton("Pause");
16: pane.add(play);
17: pane.add(stop);
18: pane.add(pause);
19: setContentPane(pane);
20: }
21:
22: public static void main(String[] arguments) {
23: Playback pb = new Playback();
24: }
25: }
When you run this application at a command line, 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.
Figure 13.2 Displaying buttons on a graphical user interface.
Many of the user components available as part of Swing can be added to a container in this manner.
Labels and Text Fields
A JLabel component displays information that cannot be modified by the user. 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 are often used to identify text fields.
A JTextField component 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 JLabel component 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();
Container pane = getContentPane();
pane.setLayout(flo);
pane.add(pageLabel);
pane.add(pageAddress);
setContentPane(pane);
Figure 13.3 shows this label and text field side-by-side. Both of the statements in this example use an argument to configure how the component should look. The pageLabel label is set up with the text Web page address: and a JLabel.RIGHT argument. This last value indicates that the label should appear flush right. JLabel.LEFT aligns the label text flush left, and JLabel.CENTER centers it. The argument used with JTextField indicates that the text field should be approximately 20 characters wide. You can also specify default text that will appear in the text field with a statement such as the following:
Figure 13.3 Displaying labels and text fields.
JTextField state = new JTextField("TX", 2);
This statement would create a JTextField object that is two characters wide and has the text TX in the field.
Check Boxes
A JCheckBox component is a box next to a line of text that can be checked or unchecked by the user. The following statements create a JCheckBox object and add it to a container:
JCheckBox jumboSize = new JCheckBox("Jumbo Size");
FlowLayout flo = new FlowLayout();
Container pane = getContentPane();
pane.setLayout(flo);
pane.add(jumboSize);
setContentPane(pane);
The argument to the JCheckBox() constructor method indicates the text to be displayed alongside the box. If you wanted the box to be checked, you could use the following statement instead:
JCheckBox jumboSize = new JCheckBox("Jumbo Size", true);
A JCheckBox can be presented singly or as part of a group. In a group of check boxes, only one can be checked at a time. To make a JCheckBox object part of a group, you have to create a ButtonGroup object. Consider the following:
JCheckBox frogLegs = new JCheckBox("Frog Leg Grande", true);
JCheckBox fishTacos = new JCheckBox("Fish Taco Platter", false);
JCheckBox emuNuggets = new JCheckBox("Emu Nuggets", false);
FlowLayout flo = new FlowLayout();
Container pane = getContentPane();
ButtonGroup meals = new ButtonGroup();
meals.add(frogLegs);
meals.add(fishTacos);
meals.add(emuNuggets);
pane.setLayout(flo);
pane.add(jumboSize);
pane.add(frogLegs);
pane.add(fishTacos);
pane.add(emuNuggets);
setContentPane(pane);
This creates three check boxes that are all grouped under the ButtonGroup object called meals. The Frog Leg Grande box is checked initially, but if the user checked one of the other meal boxes, the check next to Frog Leg Grande would disappear automatically. Figure 13.4 shows the different check boxes from this section.
Figure 13.4 Displaying check box components.
Combo Boxes
A JComboBox component is a pop-up list of choices that can also be set up to receive text input. When both options are enabled, you can select an item with your mouse or use the keyboard to enter text instead. The combo box serves a similar purpose to a group of check boxes, except that only one of the choices is visible unless the pop-up list is being displayed.
To create a JComboBox object, you have to add each of the choices after creating the object, as in the following example:
JComboBox profession = new JComboBox();
FlowLayout flo = new FlowLayout();
Container pane = getContentPane();
profession.addItem("Butcher");
profession.addItem("Baker");
profession.addItem("Candlestick maker");
profession.addItem("Fletcher");
profession.addItem("Fighter");
profession.addItem("Technical writer");
pane.setLayout(flo);
pane.add(profession);
setContentPane(pane);
This example creates a single JComboBox component that provides six choices from which the user can select. When one is selected, it appears in the display of the component. Figure 13.5 shows this example while the pop-up list of choices is being displayed.
Figure 13.5 Displaying combo box components.
To enable a JComboBox component to receive text input, its setEditable () method must be called with an argument of true, as in the following statement:
profession.setEditable(true);
This method must be called before the component is added to a container.
Text Areas
A JTextArea component is a text field that enables the user to enter more than one line of text. You can specify the width and height of the component. For example, the following statements create a JTextArea component with an approximate width of 40 characters and a height of 8 lines, and then add the component to a container:
JTextArea comments = new JTextArea(8, 40); FlowLayout flo = new FlowLayout(); Container pane = getContentPane(); pane.setLayout(flo); pane.add(comments); setContentPane(pane);
Figure 13.6 shows this example in a frame.
Figure 13.6 Displaying text area components.
You can specify a string in the JTextArea() constructor method to be displayed in the text area. You can use the newline character \n to send text to the next line, as in the following:
JTextArea desire = new JTextArea("I should have been a pair\n"
+ "of ragged claws.", 10, 25);
Panels
The last of the components you'll learn to create during this hour are panels, which are created in Swing using the JPanel class. JPanel objects are the simplest kind of container you can use in a Swing interface. The purpose of JPanel objects is to subdivide a display area into different groups of components. When the display is divided into sections, you can use different rules for how each section is organized.
You can create a JPanel object and add it to a container with the following statements:
JPanel topRow = new JPanel(); FlowLayout flo = new FlowLayout(); Container pane = getContentPane(); pane.setLayout(flo); pane.add(topRow);
Panels are often used when arranging the components in an interface, as you'll see in Hour 14, "Laying Out a User Interface."
Unlike other containers, panels do not have a content pane. Instead, you can add components by calling the panel's add() method directly. You can also assign a layout manager directly to the panel by calling its setLayout() method.
Panels can also be used when you need an area in an interface to draw something, such as an image from a graphics file.
Another convenient use of JPanel is to create your own components that can be added to other classes. This is demonstrated in this hour's workshop.
Workshop: Creating Your Own Component | Next Section

Account Sign In
View your cart