Java Reference
In-Depth Information
JPanel
with
GridLayout
JList
inside
a scroll
pane
An image is
displayed on a
Jlabel
F
IGURE
17.9
When the countries in the list are selected, corresponding images of their flags are displayed in the labels.
Here are the major steps in the program:
1. Create the user interface.
Create a list with nine country names as selection values, and place the list inside a
scroll pane. Place the scroll pane in the west of the frame. Create nine labels to be used
to display the countries' flag images. Place the labels in the panel, and place the panel
in the center of the frame.
2. Process the event.
Create a listener to implement the
valueChanged
method in the
ListSelectionListener
interface to set the selected countries' flag images in the
labels.
L
ISTING
17.5
ListDemo.java
1
import
java.awt.*;
2
import
javax.swing.*;
3
import
javax.swing.event.*;
4
5
public class
ListDemo
extends
JFrame {
6
final int
NUMBER_OF_FLAGS =
9
;
7
8
// Declare an array of Strings for flag titles
String[] flagTitles
9
private
= {
"Canada", "China"
,
"Denmark"
,
10
"France"
,
"Germany"
,
"India"
,
"Norway"
,
"United Kingdom"
,
11
"United States of America"
};
12
13
// The list for selecting countries
14
15
16
private
JList jlst =
new
JList(flagTitles);
// Declare an ImageIcon array for the national flags of 9 countries
ImageIcon[] imageIcons
17
private
= {
18
new
ImageIcon(
"image/ca.gif"
),
19
new
ImageIcon(
"image/china.gif"
),
20
new
ImageIcon(
"image/denmark.gif"
),
21
new
ImageIcon(
"image/fr.gif"
),
22
new
ImageIcon(
"image/germany.gif"
),
23
new
ImageIcon(
"image/india.gif"
),
24
new
ImageIcon(
"image/norway.gif"
),
25
new
ImageIcon(
"image/uk.gif"
),
26
new
ImageIcon(
"image/us.gif"
)
27 };
28