The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Learning Swing by Example

Example Five: LunarPhases

Topics covered in this example include: This next example, LunarPhases (in the Creating a GUI with JFC/Swing trail), is a more complicated example of how to use images in your application. As a bonus, you'll also see how to implement combo boxes. Here are two pictures of the LunarPhases application:

Screenshot of the LunarPhases application with combo box closed

Screenshot of the LunarPhases application with combo box open

In this program, the user chooses the lunar phase from the combo box, and the selected phase is shown in the lower panel. This is the first example we've seen that uses multiple panels to group components.

LunarPhases has three panels, as shown in the following figure.

A depiction of the main panel and two subpanels in LunarPhases.

In the following code in the LunarPhases constructor, we construct all three panels and add the two subpanels (selectPanel and displayPanel) to mainPanel.
   
//Create the phase selection and display panels.
selectPanel = new JPanel();
displayPanel = new JPanel();

//Add various widgets to the sub panels.
addWidgets();

//Create the main panel to contain the two sub panels.
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

//Add the select and display panels to the main panel.
mainPanel.add(selectPanel);
mainPanel.add(displayPanel);
When we put the subpanels in the main panel, it is the job of the main panel’s layout manager to make sure the subpanels are positioned correctly. The default layout manager for JPanel is FlowLayout, which simply positions components in the container from left to right in the order they’re added. In the previous code snippet, we used a layout manager called BoxLayout to position the subpanels more precisely.

Using Layout Managers

The Java platform supplies six commonly used layout managers: BorderLayout, BoxLayout, FlowLayout, GridLayout, GridBagLayout, and SpringLayout.

As we mentioned before, all JPanel objects use FlowLayout by default. On the other hand, content panes (the main containers in JApplet, JDialog, and JFrame objects) use BorderLayout by default.

As a rule, the only time you have to think about layout managers is when you create a JPanel or add components to a content pane. If you don’t like the default layout manager that a panel or content pane uses, you can use a different one, either by specifying one when creating a panel or by invoking the setLayout method. For example, here’s the code for creating a panel that uses BorderLayout:

 
JPanel pane = new JPanel(new BorderLayout());
Here’s an example of setting the layout manager of the default content pane:
 
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());

Version Note: We anticipate that in v1.5 invoking setLayout on a top-level container will have the same effect as invoking it on the top-level container’s content pane.
When you add components to a panel or a content pane, the arguments you specify to the add method depend on the layout manager that the panel or content pane is using. Layout is further discussed in Laying Out Components Within a Container (in the Creating a GUI with JFC/Swing trail).

Compound Borders

In previous examples, we've added a simple border to create a buffer of space around components. In this example, both subpanels, selectPanel and displayPanel, have a compound border, which consists of a titled border (an outlined border with a title) and an empty border (to add extra space), as shown in the following figure:

The compound border used in selectPanel.

The code for the selectPanel border follows. The displayPanel sets its own border in the same way.
// Add border around the select panel
selectPanel.setBorder(BorderFactory.createCompoundBorder(
                      BorderFactory.createTitledBorder("Select Phase"),
                      BorderFactory.createEmptyBorder(5,5,5,5)));

Combo Boxes

This example uses a combo box to present a group of choices to the user. Combo boxes can be either editable, with a text field that allows the user to enter a choice not in the group, or uneditable (the default), such as the one shown in the figure below.

A picture of a combo box

Another picture of a combo box--this combo box is dropped down.

Combo boxes are useful for displaying one-of-many choices when space is limited. The following code in LunarPhases.java (in a .java source file) creates an uneditable combo box, phaseChoices, and sets it up:
JComboBox phaseChoices = null;
...
//Create combo box with lunar phase choices.
String[] phases = { "New", "Waxing Crescent", "First Quarter",
                    "Waxing Gibbous", "Full", "Waning Gibbous", 
                    "Third Quarter", "Waning Crescent" };
phaseChoices = new JComboBox(phases);
phaseChoices.setSelectedIndex(START_INDEX);
The code initializes the combo box with an array of strings, phases. You can also put an array of icons in a combo box or initialize the combo box with a vector or custom data structure. In the last line of code, the setSelectedIndex method specifies which phase of the moon should be shown when the program starts.

Handling Events on a Combo Box

The combo box fires an action event when the user selects an item from the combo box's drop-down list. The following code from LunarPhases registers and implements an action listener on the combo box:
phaseChoices.addActionListener(this);
...
public void actionPerformed(ActionEvent event) {
    if ("comboBoxChanged".equals(event.getActionCommand())) {
        //Update the icon to display the new phase
        phaseIconLabel.setIcon(images[phaseChoices.getSelectedIndex()]);
    }
}
This action listener gets the newly selected item from the combo box, uses that item to find the image to display, and updates a label to display the image.

Multiple Images

In the CelsiusConverter program, we saw how to add a single ImageIcon to a button. The LunarPhases program uses eight images. Only one image of the eight is used at a time, so we have a choice as to whether we load all the images up front or load the images as they are needed (known as "lazy image loading"). In this example, the images are all loaded up front when the class is constructed.
final static int NUM_IMAGES = 8;
final static int START_INDEX = 3;

ImageIcon[] images = new ImageIcon[NUM_IMAGES];
...
//Get the images and put them into an array of ImageIcon.
for (int i = 0; i < NUM_IMAGES; i++) {
    String imageName = "images/image" + i + ".jpg";
    System.out.println("getting image: " + imageName);
    URL iconURL = LunarPhases.class.getResource(imageName);
    ImageIcon icon = new ImageIcon(iconURL);
    images[i] = icon;
}
Note the use of getSystemResource, a method that searches the class path to find the image files. Loading image files is discussed in detail in How to Use Icons (in the Creating a GUI with JFC/Swing trail).


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.