public class ListFrame extends JFrame
1: // Fig. 11.23: ListFrame.java
2: // Selecting colors from a JList.
3: import java.awt.FlowLayout;
4: import java.awt.Color;
5: import javax.swing.JFrame;
6: import javax.swing.JList;
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 JList colorJList; // list to display colors
15: private final String colorNames[] = { "Black", "Blue", "Cyan",
16: "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
17: "Orange", "Pink", "Red", "White", "Yellow" };
18: private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN,
19: Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY,
20: Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE,
21: Color.YELLOW };
22:
23: // ListFrame constructor add JScrollPane containing JList to JFrame
24: public ListFrame()
25: {
26: super( "List Test" );
27: setLayout( new FlowLayout() ); // set frame layout
28:
29: colorJList = new JList( colorNames ); // create with colorNames
30: colorJList.setVisibleRowCount( 5 ); // display five rows at once
31:
32: // do not allow multiple selections
33: colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
34:
35: // add a JScrollPane containing JList to frame
36: add( new JScrollPane( colorJList ) );
37:
38: colorJList.addListSelectionListener(
39: new ListSelectionListener() // anonymous inner class
40: {
41: // handle list selection events
42: public void valueChanged( ListSelectionEvent event )
43: {
44: getContentPane().setBackground(
45: colors[ colorJList.getSelectedIndex() ] );
46: } // end method valueChanged
47: } // end anonymous inner class
48: ); // end call to addListSelectionListener
49: } // end ListFrame constructor
50: } // end class ListFrame
51:
52: /**************************************************************************
53: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
54: * Pearson Education, Inc. All Rights Reserved. *
55: * *
56: * DISCLAIMER: The authors and publisher of this book have used their *
57: * best efforts in preparing the book. These efforts include the *
58: * development, research, and testing of the theories and programs *
59: * to determine their effectiveness. The authors and publisher make *
60: * no warranty of any kind, expressed or implied, with regard to these *
61: * programs or to the documentation contained in these books. The authors *
62: * and publisher shall not be liable in any event for incidental or *
63: * consequential damages in connection with, or arising out of, the *
64: * furnishing, performance, or use of these programs. *
65: *************************************************************************/