Java Reference
In-Depth Information
5
public class ListTest
6
{
7
public static void main(String[] args)
8
{
9
ListFrame listFrame = new ListFrame(); // create ListFrame
10
listFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
listFrame.setSize( 350 , 150 );
12
listFrame.setVisible( true );
13
}
14
} // end class ListTest
Fig. 12.24 | Selecting colors from a JList . (Part 2 of 2.)
Line 29 (Fig. 12.23) creates JList object colorJList . The argument to the JList
constructor is the array of Object s (in this case String s) to display in the list. Line 30 uses
JList method setVisibleRowCount to determine the number of items visible in the list.
Line 33 uses JList method setSelectionMode to specify the list's selection mode .
Class ListSelectionModel (of package javax.swing ) declares three constants that specify
a JList 's selection mode— SINGLE_SELECTION (which allows only one item to be selected
at a time), SINGLE_INTERVAL_SELECTION (for a multiple-selection list that allows selection
of several contiguous items) and MULTIPLE_INTERVAL_SELECTION (for a multiple-selection
list that does not restrict the items that can be selected).
Unlike a JComboBox , a JList does not provide a scrollbar if there are more items in the
list than the number of visible rows. In this case, a JScrollPane object is used to provide
the scrolling capability. Line 36 adds a new instance of class JScrollPane to the JFrame .
The JScrollPane constructor receives as its argument the JComponent that needs scrolling
functionality (in this case, colorJList ). Notice in the screen captures that a scrollbar cre-
ated by the JScrollPane appears at the right side of the JList . By default, the scrollbar
appears only when the number of items in the JList exceeds the number of visible items.
Lines 38-49 use JList method addListSelectionListener to register an object that
implements ListSelectionListener (package javax.swing.event ) as the listener for the
JList 's selection events. Once again, we use an instance of an anonymous inner class (lines
39-48) as the listener. In this example, when the user makes a selection from colorJList ,
method valueChanged (line 42-47) should change the background color of the List-
Frame to the selected color. This is accomplished in lines 45-46. Note the use of JFrame
method getContentPane in line 45. Each JFrame actually consists of three layers —the
background , the content pane and the glass pane . The content pane appears in front of the
background and is where the GUI components in the JFrame are displayed. The glass pane
is used to display tool tips and other items that should appear in front of the GUI compo-
nents on the screen. The content pane completely hides the background of the JFrame ;
thus, to change the background color behind the GUI components, you must change the
content pane's background color. Method getContentPane returns a reference to the
 
Search WWH ::




Custom Search