import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class ComboBoxTest extends JFrame implements ActionListener, ListDataListener, ItemListener { JButton add = new JButton("Add"); JButton remove = new JButton("Remove"); JTextField text = new JTextField(10); JComboBox theBox; public ComboBoxTest() { super("ComboBoxTest"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); String[] theElements = {"one", "two", "three", "four"}; //Create a combo box containing the String objects above. theBox = new JComboBox(theElements); theBox.getModel().addListDataListener(this); theBox.addActionListener(this); theBox.addItemListener(this); //Do not show more then three elements. theBox.setMaximumRowCount(3); //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(theBox, "Center"); //Show the frame. pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { //Add an element to the list. theBox.addItem(text.getText()); } else if (e.getSource() == remove) { //Remove all elements from the list. theBox.removeAllItems(); } else if (e.getSource() == theBox) { System.out.println("action performed"); System.out.println(e.toString() + "\n"); } } public void itemStateChanged(ItemEvent e) { System.out.println("item state changed"); System.out.println(e.toString() + "\n"); } 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 static void main(String[] args) { new ComboBoxTest(); } }