1  import java.awt.*;
  2  import java.awt.event.*;
  3  import javax.swing.*;
  4  
  5  public class ComboBoxCellRendererDemo extends JApplet {
  6    private final static int NUMBER_OF_NATIONS = 7;
  7    private String[] nations = new String[] {"Denmark",
  8      "Germany", "China", "India", "Norway", "UK", "US"};
  9    private ImageIcon[] icons = new ImageIcon[NUMBER_OF_NATIONS];
 10    private ImageIcon[] bigIcons = new ImageIcon[NUMBER_OF_NATIONS];
 11  
 12    // Create a combo box model
 13    private DefaultComboBoxModel model = new DefaultComboBoxModel();
 14  
 15    // Create a combo box with the specified model
 16    private JComboBox jcboCountries = new JComboBox(model);
 17  
 18    // Create a list cell renderer
 19    private MyListCellRenderer renderer = new MyListCellRenderer();
 20  
 21    // Create a label for displaying iamge
 22    private JLabel jlblImage = new JLabel("", JLabel.CENTER);
 23  
 24    /** Construct the applet */
 25    public ComboBoxCellRendererDemo() {
 26      // Load small and large image icons
 27      for (int i = 0; i < NUMBER_OF_NATIONS; i++) {
 28        icons[i] = new ImageIcon(getClass().getResource(
 29          "/image/flagIcon" + i + ".gif"));
 30        model.addElement(new Object[]{icons[i], nations[i]});
 31  
 32        bigIcons[i] = new ImageIcon(getClass().getResource(
 33          "/image/flag" + i + ".gif"));
 34      }
 35  
 36      // Set list cell renderer for the combo box
 37      jcboCountries.setRenderer(renderer);
 38      jlblImage.setIcon(bigIcons[0]);
 39      add(jcboCountries, java.awt.BorderLayout.NORTH);
 40      add(jlblImage, java.awt.BorderLayout.CENTER);
 41  
 42      // Register listener
 43      jcboCountries.addActionListener(new ActionListener() {
 44        @Override
 45        public void actionPerformed(java.awt.event.ActionEvent e) {
 46          jlblImage.setIcon(bigIcons[jcboCountries.getSelectedIndex()]);
 47        }
 48      });
 49    }
 50  
 51    /** Main method */
 52    public static void main(String[] args) {
 53      ComboBoxCellRendererDemo applet = new ComboBoxCellRendererDemo();
 54      JFrame frame = new JFrame();
 55      //EXIT_ON_CLOSE == 3
 56      frame.setDefaultCloseOperation(3);
 57      frame.setTitle("ComboBoxCellRendererDemo");
 58      frame.getContentPane().add(applet, BorderLayout.CENTER);
 59      applet.init();
 60      applet.start();
 61      frame.setSize(400,320);
 62      frame.setLocationRelativeTo(null);
 63      frame.setVisible(true);
 64    }
 65  }