1  import java.awt.*;
  2  import javax.swing.*;
  3  import javax.swing.event.*;
  4  
  5  public class ListDemo extends JFrame {
  6    final int NUMBER_OF_FLAGS = 9;
  7  
  8    // Declare an array of Strings for flag titles
  9    private String[] flagTitles = {"Canada", "China", "Denmark",
 10      "France", "Germany", "India", "Norway", "United Kingdom",
 11      "United States of America"};
 12  
 13    // The list for selecting countries
 14    private JList jlst = new JList(flagTitles);
 15  
 16    // Declare an ImageIcon array for the national flags of 9 countries
 17    private ImageIcon[] imageIcons = {
 18      new ImageIcon("image/ca.gif"),
 19      new ImageIcon("image/china.gif"),
 20      new ImageIcon("image/denmark.gif"),
 21      new ImageIcon("image/fr.gif"),
 22      new ImageIcon("image/germany.gif"),
 23      new ImageIcon("image/india.gif"),
 24      new ImageIcon("image/norway.gif"),
 25      new ImageIcon("image/uk.gif"),
 26      new ImageIcon("image/us.gif")
 27    };
 28  
 29    // Arrays of labels for displaying images
 30    private JLabel[] jlblImageViewer = new JLabel[NUMBER_OF_FLAGS];
 31  
 32    public static void main(String[] args) {
 33      ListDemo frame = new ListDemo();
 34      frame.setSize(650, 500);
 35      frame.setTitle("ListDemo");
 36      frame.setLocationRelativeTo(null); // Center the frame
 37      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 38      frame.setVisible(true);
 39    }
 40  
 41    public ListDemo() {
 42      // Create a panel to hold nine labels
 43      JPanel p = new JPanel(new GridLayout(3, 3, 5, 5));
 44  
 45      for (int i = 0; i < NUMBER_OF_FLAGS; i++) {
 46        p.add(jlblImageViewer[i] = new JLabel());
 47        jlblImageViewer[i].setHorizontalAlignment
 48          (SwingConstants.CENTER);
 49      }
 50  
 51      // Add p and the list to the frame
 52      add(p, BorderLayout.CENTER);
 53      add(new JScrollPane(jlst), BorderLayout.WEST);
 54  
 55      // Register listeners
 56      jlst.addListSelectionListener(new ListSelectionListener() {
 57        @Override /** Handle list selection */
 58        public void valueChanged(ListSelectionEvent e) {
 59          // Get selected indices
 60          int[] indices = jlst.getSelectedIndices();
 61  
 62          int i;
 63          // Set icons in the labels
 64          for (i = 0; i < indices.length; i++) {
 65            jlblImageViewer[i].setIcon(imageIcons[indices[i]]);
 66          }
 67  
 68          // Remove icons from the rest of the labels
 69          for (; i < NUMBER_OF_FLAGS; i++) {
 70            jlblImageViewer[i].setIcon(null);
 71          }
 72        }
 73      });
 74    }
 75  }