Java Reference
In-Depth Information
JFrame 's content pane (an object of class Container ). In line 45, we then use that reference
to call method setBackground , which sets the content pane's background color to an ele-
ment in the colors array. The color is selected from the array by using the selected item's
index. JList method getSelectedIndex returns the selected item's index. As with arrays
and JComboBox es, JList indexing is zero based.
12.13 Multiple-Selection Lists
A multiple-selection list enables the user to select many items from a JList (see the output
of Fig. 12.26). A SINGLE_INTERVAL_SELECTION list allows selecting a contiguous range of
items. To do so, click the first item, then press and hold the Shift key while clicking the
last item in the range. A MULTIPLE_INTERVAL_SELECTION list (the default) allows continu-
ous range selection as described for a SINGLE_INTERVAL_SELECTION list. Such a list also al-
lows miscellaneous items to be selected by pressing and holding the Ctrl key while clicking
each item to select. To deselect an item, press and hold the Ctrl key while clicking the item
a second time.
The application of Figs. 12.25-12.26 uses multiple-selection lists to copy items from
one JList to another. One list is a MULTIPLE_INTERVAL_SELECTION list and the other is a
SINGLE_INTERVAL_SELECTION list. When you execute the application, try using the selec-
tion techniques described previously to select items in both lists.
1
// Fig. 12.25: MultipleSelectionFrame.java
2
// JList that allows multiple selections.
3
import java.awt.FlowLayout;
4
import java.awt.event.ActionListener;
5
import java.awt.event.ActionEvent;
6
import javax.swing.JFrame;
7
import javax.swing.JList;
8
import javax.swing.JButton;
9
import javax.swing.JScrollPane;
10
import javax.swing.ListSelectionModel;
11
12
public class MultipleSelectionFrame extends JFrame
13
{
14
private final JList<String> colorJList; // list to hold color names
15
private final JList<String> copyJList; // list to hold copied names
16
private JButton copyJButton; // button to copy selected names
17
private static final String[] colorNames = { "Black" , "Blue" , "Cyan" ,
18
"Dark Gray" , "Gray" , "Green" , "Light Gray" , "Magenta" , "Orange" ,
19
"Pink" , "Red" , "White" , "Yellow" };
20
21
// MultipleSelectionFrame constructor
22
public MultipleSelectionFrame()
23
{
24
super ( "Multiple Selection Lists" );
25
setLayout( new FlowLayout());
26
27
colorJList = new JList<String>(colorNames); // list of color names
28
colorJList.setVisibleRowCount( 5 ); // show five rows
Fig. 12.25 | JList that allows multiple selections. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search