package examples; import java.awt.*; import javax.swing.*; import javax.swing.event.*; /** * CS401 Example 37 * * Demonstrates the use of the JList GUI component. The program displays a list * of color names in a JList. When the user selects one of them, the background * of the window is changed to be that color. * * @author PJ Dillon */ public class ex37 implements ListSelectionListener { private JList list; private Container container; private static Color[] colors = {Color.black, Color.WHITE, Color.GREEN, Color.GRAY, Color.BLUE, Color.orange, Color.cyan, Color.magenta, Color.yellow, Color.red}; private static String[] names = {"Black", "White", "Green", "Gray", "Blue", "Orange", "Cyan", "Magenta", "Yellow", "Red"}; public ex37() { JFrame window = new JFrame("Example 37"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); container = window.getContentPane(); container.setLayout(new FlowLayout()); /* * Create the list is much the same way we created a JComboBox, passing it * an array that initializes its model to display the items passed in. */ list = new JList(names); list.addListSelectionListener(this); list.setVisibleRowCount(5); /* * We want the user to be restricted to only selecting one of the list * values at a time since the background can only be one color at a time. */ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); /* * The list may need more screen space that it can use. If this is the case, * we won't see the part of the list that extends off the window. In this * case, we can use a JScollPane, which is a container that will * automatically display a scroll bar if its component is too large for the * available space. */ container.add(new JScrollPane(list)); window.setSize(400, 150); window.setVisible(true); } /** * The JList component generates a different type of event, a * ListSelectionEvent, which requires a different listener. When an event of * this type is throw, the valueChanged() method is called of any associated * listeners. */ public void valueChanged(ListSelectionEvent e) { container.setBackground(colors[list.getSelectedIndex()]); } public static void main(String[] args) { new ex37(); } }