Java Reference
In-Depth Information
7
import javax.swing.JScrollPane;
8
import javax.swing.event.ListSelectionListener;
9
import javax.swing.event.ListSelectionEvent;
10
import javax.swing.ListSelectionModel;
11
12
public class ListFrame extends JFrame
13
{
14
private final JList<String> colorJList; // list to display colors
15
private static final String[] colorNames = { "Black" , "Blue" , "Cyan" ,
16
"Dark Gray" , "Gray" , "Green" , "Light Gray" , "Magenta" ,
17
"Orange" , "Pink" , "Red" , "White" , "Yellow" };
18
private static final Color[] colors = { Color.BLACK , Color.BLUE ,
19
Color.CYAN , Color.DARK_GRAY , Color.GRAY , Color.GREEN ,
20
Color.LIGHT_GRAY , Color.MAGENTA , Color.ORANGE , Color.PINK ,
21
Color.RED , Color.WHITE , Color.YELLOW };
22
23
// ListFrame constructor add JScrollPane containing JList to JFrame
24
public ListFrame()
25
{
26
super ( "List Test" );
27
setLayout( new FlowLayout());
28
29
colorJList = new JList<String>(colorNames); // list of colorNames
colorJList.setVisibleRowCount( 5 ); // display five rows at once
30
31
32
// do not allow multiple selections
colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
33
34
35
// add a JScrollPane containing JList to frame
add( new JScrollPane(colorJList));
36
37
38
colorJList.addListSelectionListener(
39
new ListSelectionListener() // anonymous inner class
40
{
41
// handle list selection events
42
@Override
43
public void valueChanged(ListSelectionEvent event)
44
{
45
getContentPane().setBackground(
46
colors[
colorJList.getSelectedIndex()
]);
47
}
48
}
49
);
50
}
51
} // end class ListFrame
Fig. 12.23 | JList that displays a list of colors. (Part 2 of 2.)
1
// Fig. 12.24: ListTest.java
2
// Selecting colors from a JList.
3
import javax.swing.JFrame;
4
Fig. 12.24 | Selecting colors from a JList . (Part 1 of 2.)
Search WWH ::




Custom Search