Java Reference
In-Depth Information
Listening to JList Events with a ListSelectionListener
If you want to know when elements of a JList have been selected, you need to
attach a ListSelectionListener to the JList or the ListSelectionModel . The
addListSelectionListener() and removeListenerListener() methods of the JList
only delegate to the underlying ListSelectionModel . When the set of selected elements
changes, attached listener objects are notified. The interface definition follows:
public interface ListSelectionListener extends EventListener {
public void valueChanged(ListSelectionEvent e);
}
The ListSelectionEvent instance received by the listener describes the range of affected
elements for this selection event, as well as whether or not the selection is still changing, as
shown in Table 13-8. When a user is still altering selected elements, with a valueIsAdjusting
setting of true , you might want to delay performing costly operations such as drawing a high-
resolution graphics presentation.
Table 13-8. ListSelectionEvent Properties
Property Name
Data Type
Access
firstIndex
int
Read-only
lastIndex
int
Read-only
valueIsAdjusting
boolean
Read-only
In order to demonstrate selection with a JList , the program shown in Listing 13-8 adds a
JTextArea to a window to show the output of the selection listener. The listener prints out the
currently selected items by item position and value.
Listing 13-8. Rendering Complex List Cells Sample
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.io.*;
public class SelectingJListSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
String labels[] = {"Chardonnay", "Sauvignon", "Riesling", "Cabernet",
"Zinfandel", "Merlot", "Pinot Noir", "Sauvignon Blanc", "Syrah",
"Gewürztraminer"};
JFrame frame = new JFrame("Selecting JList");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Search WWH ::




Custom Search