import java.awt.*; import javax.swing.*; import java.awt.event.*; class TestJComboBox { /* Declare two arrays, one of string names, * one of matching Colors. */ private static final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow"}; private static final Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow }; public static void main(String[] args){ /* Create a JFrame, set title, and get contents pane. */ JFrame frame = new JFrame(); frame.setTitle("A JComboBox"); Container pane = frame.getContentPane(); pane.setLayout(new FlowLayout()); /* Create the color menu, and add ItemListener, with * implementation as inner class. */ JComboBox colorMenu = new JComboBox(colorNames); colorMenu.setFont(new Font("Sansserif",Font.PLAIN,24)); colorMenu.addItemListener( new ItemListener(){ /* Method to implement is itemStateChanged.*/ public void itemStateChanged(ItemEvent e){ /* Get first a pointer to the JComboBox * that caused the event... */ JComboBox jcb = (JComboBox) e.getSource(); /* ... the partent of which is out pane */ (jcb.getParent()).setBackground(colors[jcb.getSelectedIndex()]); } } ); pane.add(colorMenu); frame.setSize(300,300); frame.show(); frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){System.exit(0);} }); } }