Java Reference
In-Depth Information
javax.swing.JComponent
The
get
and
set
methods for these data fields are provided
in the class, but omitted in the UML diagram for brevity.
javax.swing.JList
-selectedIndex: int
-selectedIndices: int[]
-selectedValue: Object
-visibleRowCount: int
The index of the first selected item.
An array of all of the selected indices in increasing order.
The first selected item in the list.
The number of visible rows displayed without a scrollbar
(default: 8).
-selectionBackground: Color
The background color of the selected cells.
The foreground color of the selected cells.
The selection mode for the list.
-selectionForeground: Color
-selectionMode: int
+JList()
+JList(items: Object[])
Creates a default empty list.
Creates a list that contains the elements in the specified array.
Adds a
ListSelectionListener
to this object.
+addListSelectionListener(listener:
ListSelectionListener): void
F
IGURE
17.7
JList
enables you to select multiple items from a set of items.
(a) Single selection
(b) Single-interval
selection
(c) Multiple-interval
selection
F
IGURE
17.8
JList
has three selection modes: single selection, single-interval selection,
and multiple-interval selection.
The following statements create a list with six items,
red
foreground,
white
background,
pink
selection foreground,
black
selection background, and visible row count
4
.
1 JList jlst =
new
JList(
new
String[]
2 {
"Item 1"
,
"Item 2"
,
"Item 3"
,
"Item 4"
,
"Item 5"
,
"Item 6"
});
3 jlst.setForeground(Color.RED);
4 jlst.setBackground(Color.WHITE);
5 jlst.setSelectionForeground(Color.PINK);
6 jlst.setSelectionBackground(Color.BLACK);
7 jlst.setVisibleRowCount(
4
);
Lists do not scroll automatically. To make a list scrollable, create a scroll pane and add the list
to it.
JList
fires
javax.swing.event.ListSelectionEvent
to notify the listeners of the
selections. The listener must implement the
valueChanged
handler in the
javax.swing.event.ListSelectionListener
interface to process the event.
Listing 17.5 gives a program that lets users select countries in a list and displays the flags
of the selected countries in the labels. Figure 17.9 shows a sample run of the program.