import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JCBExample1 // demo for a JComboBox - simple program, select a String from the JComboBox out of an array { // and use the array index of the selected item to select a String from a second array to display public static void main(String[] args) // in a JLabel, this GUI has just the JComboBox and JLabel { JFrame frame=new JFrame(""); frame.setSize(350,80); JCBPanel p=new JCBPanel(); frame.add(p); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static class JCBPanel extends JPanel implements ItemListener { private JLabel lab; // to appear on the right hand side in response to the combo box selection private JComboBox box; // drop down box private String[] list={"Apple", "Banana", "Cherry", "Date", "Fig", "Orange", "Peach"}; // items for the combo box private String[] descr={"One every day is good for you", // items to display in the JLabel "Don't slip on that peal", "3 of these and you win the jackpot", "Lots and lots of sugar", "Can I make that into a cookie?", "No thanks, I'd rather have juice", "From Georgia?"}; public JCBPanel() // note: we could have instantiated list and descr here { lab=new JLabel(" "); // start with an initially blank JLabel box=new JComboBox(list); // instantiate the JComboBox with the array list box.addItemListener(this); // use ItemListener to handle any itemStateChanged events setLayout(new BorderLayout()); // create the layout for the JPanel add(box,BorderLayout.CENTER); add(lab,BorderLayout.EAST); } public void itemStateChanged(ItemEvent e) // method is invoked when the JComboBox's selection changes { lab.setText(descr[box.getSelectedIndex()]); // obtain the index of the selected item in the JComboBox } // and use the same index to pull out the corresponding String } // from list and put this in the JLabel }