Instead of obtaining the index of a selection, you can obtain the value associated with
the selection by calling getSelectedValue( ):
Object getSelectedValue( )
It returns a reference to the first selected value. If no value has been selected, it returns null.
The following applet demonstrates a simple JList, which holds a list of cities. Each time
a city is selected in the list, a ListSelectionEvent is generated, which is handled by the
valueChanged( ) method defined by ListSelectionListener. It responds by obtaining the
index of the selected item and displaying the name of the selected city in a label.
// Demonstrate JList.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="JListDemo" width=200 height=120>
</applet>
*/
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle",
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home