Java Reference
In-Depth Information
Figure 7.6
The
JList
component provides a list
of items for the user to
choose. The component
can allow for single or
multiple item selections.
Here, for our
ListPanel
class in
UITestApplet
,
only one item can be
selected.
Instead of an
ActionListener
, the
JList
sends its events to a
ListSelectionListener
(which appears in the
javax.swing.event
package). This version of our
ControlPanel
implements the
ListSelec-
tionListener
interface and provides a
valueChanged()
method. The
selected item is determined from the list and the
OutputPanel
's background is
set to that color.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
/**
* The ListPanel holds the JList component with items
* that determine the color of the output panel.
**/
public class
ListPanel extends
JPanel
implements ListSelectionListener
{
OutputPanel fOutputPanel;
/** Constructor adds a JList to the panel. **/
ListlPanel (OutputPanel output
-
panel) {
fOutputPanel
=
output
-
panel;
String [] colors
={
"
Red
"
,
"
Green
"
,
"
Blue
"
,
"
Yellow
"
,
"
White
"
,
"
Black
"}
;
JList color
-
list
=
new JList (colors);
// Show only 4 items in the list at a time.
color
-
list.setVisibleRowCount (4);
Search WWH ::
Custom Search