Java Reference
In-Depth Information
29
// Arrays of labels for displaying images
30
private
JLabel[] jlblImageViewer =
new
JLabel[NUMBER_OF_FLAGS];
31
32
public static void
main(String[] args) {
33 ListDemo frame =
new
ListDemo();
34 frame.setSize(
650
,
500
);
35 frame.setTitle(
"ListDemo"
);
36 frame.setLocationRelativeTo(
null
);
// Center the frame
37 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
38 frame.setVisible(
true
);
39 }
40
41
public
ListDemo() {
42
// Create a panel to hold nine labels
43 JPanel p =
new
JPanel(
new
GridLayout(
3
,
3
,
5
,
5
));
44
45
for
(
int
i =
0
; i < NUMBER_OF_FLAGS; i++) {
46 p.add(jlblImageViewer[i] =
new
JLabel());
47 jlblImageViewer[i].setHorizontalAlignment
48 (SwingConstants.CENTER);
49 }
50
51
// Add p and the list to the frame
52 add(p, BorderLayout.CENTER);
53 add(
new
JScrollPane(jlst), BorderLayout.WEST);
54
55
// Register listeners
56 jlst.addListSelectionListener(
new
ListSelectionListener() {
57 @Override
/** Handle list selection */
58
create frame
create UI
public void
valueChanged(ListSelectionEvent e) {
event handler
59
// Get selected indices
60
int
[] indices = jlst.getSelectedIndices();
61
62
int
i;
63
// Set icons in the labels
64
for
(i =
0
; i < indices.length; i++) {
65 jlblImageViewer[i].setIcon(imageIcons[indices[i]]);
66 }
67
68
// Remove icons from the rest of the labels
69
for
(; i < NUMBER_OF_FLAGS; i++) {
70 jlblImageViewer[i].setIcon(
null
);
71 }
72 }
73 });
74 }
75 }
The anonymous inner-class listener listens to
ListSelectionEvent
for handling the selec-
tion of country names in the list (lines 56-73).
ListSelectionEvent
and
ListSelectionListener
are defined in the
javax.swing.event
package, so this pack-
age is imported into the program (line 3).
The program creates an array of nine labels for displaying flag images for nine countries.
The program loads the images of the nine countries into an image array (lines 17-27) and cre-
ates a list of the nine countries in the same order as in the title array (lines 9-11). Thus, the
index
0
of the image array corresponds to the first country in the list.
The list is placed in a scroll pane (line 53) so that it can be scrolled when the number of
items in the list extends beyond the viewing area.