/** ListPanel.java -- Create a panel that shows a list of file names * for the user to choose. Here, we use a JList, which accepts an * array or vector of items. What's unique here is that we are * using a ListSelectionListener interface to listen for the event * of someone choosing something on the list. */ import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class ListPanel extends JPanel { private JLabel label; private JList list; public ListPanel(JLabel l) { label = l; String [] fileName = { "lagoon.jpg", "tower.jpg", "puppy.jpg", "poor-kitty.jpg", "horse.jpg" }; list = new JList(fileName); list.addListSelectionListener(new ListListener()); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add(list); } private class ListListener implements ListSelectionListener { // Find out which file the user chose, and display the appropriate // image in the JLabel object that was passed to the constructor. public void valueChanged(ListSelectionEvent e) { if (list.isSelectionEmpty()) label.setIcon(null); else { String fileName = (String) list.getSelectedValue(); ImageIcon image = new ImageIcon(fileName); label.setIcon(image); } } } }