import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class ListTest extends JFrame implements ActionListener, ListDataListener, ListSelectionListener { JButton add = new JButton("Add"); JButton remove = new JButton("Remove"); JTextField text = new JTextField(10); JList theList; DefaultListModel model; public ListTest() { super("ListTest"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //Explicitly defining a model is the only way we can //change the list contents on the fly. model = new DefaultListModel(); //Create a list using the model above. theList = new JList(model); //Add some elements to the list. model.addElement("one"); model.addElement("two"); model.addElement("three"); model.addElement("four"); model.addListDataListener(this); theList.addListSelectionListener(this); //Do not show more then three elements. theList.setVisibleRowCount(3); //Support scrolling by placing the list in a scroll pane. JScrollPane scroll = new JScrollPane(theList); //Build the UI. JPanel addRemove = new JPanel(); remove.addActionListener(this); addRemove.add(remove); add.addActionListener(this); addRemove.add(add); addRemove.add(text); Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(addRemove, "North"); c.add(scroll, "Center"); //Show the frame. pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { //Add an element to the list. model.addElement(text.getText()); } else if (e.getSource() == remove) { //Remove all elements from the list. model.removeAllElements(); } } public void intervalAdded(ListDataEvent e) { System.out.println("interval added"); System.out.println(e.toString() + "\n"); } public void intervalRemoved(ListDataEvent e) { System.out.println("interval removed"); System.out.println(e.toString() + "\n"); } public void contentsChanged(ListDataEvent e) { System.out.println("contents changed"); System.out.println(e.toString() + "\n"); } public void valueChanged(ListSelectionEvent e) { System.out.println("value changed"); System.out.println(e.toString() + "\n"); } public static void main(String[] args) { new ListTest(); } }