Java Reference
In-Depth Information
Figure 13-9 shows the appearance of the running program.
Figure 13-9. Listening for JList selections
The example in Listing 13-8 prints out only the currently selected items when it is not
doing a rapid update (when isAdjusting reports false ). Otherwise, the program merely
reports the starting and ending range of selection changes, as well as the adjusting status. The
example examines the selectedIndices and selectedValues properties of JList to get an ordered
list of selected items. The selectedIndices and selectedValues arrays are ordered in the same
way, so a particular element of the data model will show up in the same position in both lists.
There's no special selection event for double-clicking an item in the list. If you're interested in
double-click events, you need to fall back to the AWT MouseEvent / MouseListener pair. Adding the
following code to the program in Listing 13-8 will add appropriate text to the JTextArea for
double-click events. The key method here is the public int locationToIndex(Point location)
method of JList , which attempts to map screen coordinates to list elements.
import java.awt.event.*;
...
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList)mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
textArea.append("Double-clicked on: " + o.toString());
textArea.append(System.getProperty("line.separator"));
}
}
}
};
jlist.addMouseListener(mouseListener);
Note The JList class also provides the public Point indexToLocation(int index) method, which
produces the reverse behavior, returning a Point as the origin of the provided index .
 
Search WWH ::




Custom Search