TestListWidgets.java
Select all
/* TestListWidgets.java David Klick CIS 260 2/14/06 Demonstrates use of JList and JComboBox. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class TestListWidgets extends JFrame implements ListSelectionListener, ActionListener { JList lst; JComboBox cbo; public static void main(String[] args) { TestListWidgets app = new TestListWidgets("List Widget Test"); } public TestListWidgets() { this(""); } public TestListWidgets(String title) { super(title); init(); } private void init() { // make Window shut down graphics thread properly setDefaultCloseOperation(EXIT_ON_CLOSE); // get content pane and set to GridLayout Container c = getContentPane(); c.setLayout(new GridLayout(1,2)); // create widgets String[] colors = { "red", "blue", "green", "white", "yellow", "pink", "tan", "black", "orange", "maroon", "beige" }; String[] shortNames = { "Bob", "Carol", "Ted", "Alice", "Dave", "Sue", "Sam", "Pam", "Art", "Ali", "Beth", "Cindy", "Ed", "Fred" }; lst = new JList(colors); cbo = new JComboBox(shortNames); // set some properties of the list widgets lst.setVisibleRowCount(5); lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); cbo.setMaximumRowCount(7); // add widgets c.add(new JScrollPane(lst)); c.add(cbo); // add event handlers (listeners) lst.addListSelectionListener(this); cbo.addActionListener(this); // make it live setSize(200, 100); setVisible(true); } public void actionPerformed(ActionEvent e) { String item = (String)(((JComboBox) (e.getSource())).getSelectedItem()); System.out.println("You selected " + item); } public void valueChanged(ListSelectionEvent e) { Object[] items = (((JList) (e.getSource())).getSelectedValues()); System.out.println("You selected"); if (items.length == 0) System.out.println(" * nothing *"); else for (Object s : items) System.out.println(" " + s); } }