Handling Selections

The JList class in Swing depends on a second model, this one to monitor the elements that have been selected by the user. As with the list data model, the programmer is given many places in which standard behavior can be altered or replaced when dealing with selections. Swing uses a simple interface for models that handle list selections (ListSelectionModel) and provides a default implementation (DefaultList-SelectionModel).
 

The ListSelectionModel Interface

The ListSelectionModel interface outlines the methods necessary for managing list selections. Selections are represented by a series of ranges, where each range is defined by its endpoints. For example, if the elements One, Two, Three, Six, Seven, and Nine were selected in the opening example earlier, the list selection model would contain three entries that specified the ranges {1,3}, {6,7}, and {9,9}. All selection indices are zero-based, and the ranges are closed, meaning both endpoint indices are included within the selection. If only one element is present in a range, such as with Nine, both endpoints are identical.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class SimpleList2 extends JPanel {

	String label[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
			"Seven", "Eight", "Nine", "Ten", "Eleven" };
	JList list;

	public SimpleList2() {
		setLayout(new BorderLayout());

		list = new JList(label);
		JButton button = new JButton("Print");
		JScrollPane pane = new JScrollPane(list);

		DefaultListSelectionModel m = new DefaultListSelectionModel();
		m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		m.setLeadAnchorNotificationEnabled(false);
		list.setSelectionModel(m);

		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				System.out.println(e.toString());
			}
		});
		button.addActionListener(new PrintListener());

		add(pane, BorderLayout.NORTH);
		add(button, BorderLayout.SOUTH);
	}

	public static void main(String s[]) {
		JFrame frame = new JFrame("List Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new SimpleList2());
		frame.pack();
		frame.setVisible(true);
	}

	// An inner class to respond to clicks of the Print button
	class PrintListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int selected[] = list.getSelectedIndices();
			System.out.println("Selected Elements:  ");

			for (int i = 0; i < selected.length; i++) {
				String element = (String) list.getModel().getElementAt(
						selected[i]);
				System.out.println("  " + element);
			}
		}
	}
}