Example Five: LunarPhases

 <  Day Day Up  >  

graphics/cd_icon.gif

This section LunarPhases , [8] 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. Figure 9 shows two pictures of the LunarPhases application.

[8] To run LunarPhases using Java Web Start, click the LunarPhases link on the RunExamples/learn.html page on the CD. You can find the source files here: JavaTutorial/uiswing/learn/example-1dot4/index.html#LunarPhases .

Figure 9. Two screenshots of the LunarPhases application.

graphics/02fig09.gif

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 Figure 10.

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

graphics/02fig10.gif

The following code constructs all three panels and adds the two subpanels ( selectPanel and displayPanel ) to the mainPanel .

 //Create the phase selection and display panels. selectPanel = new JPanel(); displayPanel = new JPanel(); //Add various widgets to the subpanels. 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 . [9]

[9] SpringLayout was added in release 1.4 of the Java platform.

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 Chapter 4, Laying Out Components within a Container (page 87). Be sure to also check the how-to sections for particular layout managers in Chapter 8 for details.

Compound Borders

In previous examples, we 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 Figure 11.

Figure 11. The compound border used in selectPanel .

graphics/02fig11.jpg

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 Figure 12.

Figure 12. An uneditable combo box, before and after the user clicks it.

graphics/02fig12.gif

Combo boxes are useful for displaying one-of-many choices when space is limited. This code in LunarPhases.java 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 a combo box with a vector or custom data structure. [10] In the last line of code, the setSelectedIndex method specifies which phase of the moon should be shown when the program starts.

[10] To put other types of objects in a combo box or to customize how the items in a combo box look, you need to write a custom renderer. An editable combo box would also need a custom editor. See How to Use Combo Boxes (page 176) in Chapter 7 for details.

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 is used at a time, so we have a choice as to whether we load all of them up front or load them as needed (known as "lazy image loading"). In this example, all of the images are 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 getResource , a method that searches the class path to find the image files. Loading image files is discussed in detail in How to Use Icons (page 603) in Chapter 9.

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net