Java Reference
In-Depth Information
59 add(descriptionPanel, BorderLayout.CENTER);
60
61 // Register listener
62 jcbo.addItemListener( new ItemListener() {
63 @Override /** Handle item selection */
64 public void itemStateChanged(ItemEvent e) {
65 setDisplay(jcbo.getSelectedIndex());
66 }
67 });
68 }
69
70 /** Set display information on the description panel */
71 public void setDisplay( int index) {
72 descriptionPanel.setTitle(flagTitles[index]);
73 descriptionPanel.setImageIcon(flagImage[index]);
74 descriptionPanel.setDescription(flagDescription[index]);
75 }
76 }
listener
The listener listens to ItemEvent from the combo box and implements ItemListener
(lines 62-67). Instead of using ItemEvent , you could rewrite the program to use
ActionEvent for handling combo-box item selection.
The program stores the flag information in three arrays: flagTitles , flagImage , and
flagDescription (lines 7-25). The array flagTitles contains the names of nine coun-
tries, the array flagImage contains images of the nine countries' flags, and the array
flagDescription contains descriptions of the flags.
The program creates an instance of DescriptionPanel (line 28), which was presented in
Listing 17.2, DescriptionPanel.java. The program creates a combo box with initial values
from flagTitles (line 31). When the user selects an item in the combo box, the
itemStateChanged handler is executed. The handler finds the selected index and sets its
corresponding flag title, flag image, and flag description on the panel.
17.9 How do you create a combo box and add three items to it?
17.10 How do you retrieve an item from a combo box? How do you retrieve a selected item
from a combo box?
17.11 How do you get the number of items in a combo box? How do you retrieve an item at
a specified index in a combo box?
17.12 What events would a JComboBox fire upon selecting a new item?
Check
Point
17.5 Lists
A list is a component that basically performs the same function as a combo box, but it
enables the user to choose a single value or multiple values.
Key
Point
The Swing JList is very versatile. Figure 17.7 lists several frequently used constructors and
methods in JList .
selectionMode is one of the three values ( SINGLE_SELECTION ,
SINGLE_INTERVAL_SELECTION , and MULTIPLE_INTERVAL_SELECTION ) defined in
javax.swing.ListSelectionModel that indicate whether a single item, single-interval
item, or multiple-interval item can be selected. Single selection allows only one item to
be selected. Single-interval selection allows multiple selections, but the selected items
must be contiguous. Multiple-interval selection allows selections of multiple contiguous
items without restrictions, as shown in Figure 17.8. The default value is
MULTIPLE_INTERVAL_SELECTION .
 
 
Search WWH ::




Custom Search