JList Example
This JList example implements a small list of strings. Other object types can be used in the JList. Note how the ListSelectionListener determines the item selected.
The user can select more than one JList item at a time by using the Ctrl or Shift keys when making a selection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// JList Example
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class JListExample {
public static void main(String[] args) {
JList jlist = new JList(new String[] {
"Latte","Mocha","Java","Americano",
"Espresso","De-caf","Arabica"
});
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
JList jListSource = (JList)e.getSource();
Object[] selection = jListSource.getSelectedValues();
if (!e.getValueIsAdjusting()) {
System.out.println("----");
for (int i = 0; i < selection.length; i++)
System.out.println("selection = "+selection[i]);
}
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(jlist);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
10-13 This JList constructor takes an array of String objects as its parameter.
