Java Reference
In-Depth Information
Fig. 12.26
|
Testing
MultipleSelectionFrame
. (Part 2 of 2.)
Line 27 of Fig. 12.25 creates
JList
colorJList
and initializes it with the
String
s in
the array
colorNames
. Line 28 sets the number of visible rows in
colorJList
to
5
. Lines
29-30 specify that
colorJList
is a
MULTIPLE_INTERVAL_SELECTION
list. Line 31 adds a
new
JScrollPane
containing
colorJList
to the
JFrame
. Lines 51-57 perform similar
tasks for
copyJList
, which is declared as a
SINGLE_INTERVAL_SELECTION
list. If a
JList
does not contain items, it will not diplay in a
FlowLayout
. For this reason, lines 53-54 use
JList
methods
setFixedCellWidth
and
setFixedCellHeight
to set
copyJList
's width
to 100 pixels and the height of each item in the
JList
to 15 pixels, respectively.
Normally, an event generated by another GUI component (known as an
external
event
) specifies when the multiple selections in a
JList
should be processed. In this
example, the user clicks the
JButton
called
copyJButton
to trigger the event that copies
the selected items in
colorJList
to
copyJList
.
Lines 34-47 declare, create and register an
ActionListener
for the
copyJButton
.
When the user clicks
copyJButton
, method
actionPerformed
(lines 38-45) uses
JList
method
setListData
to set the items displayed in
copyJList
. Lines 43-44 call
color-
JList
's method
getSelectedValuesList
, which returns a
List<String>
(because the
JList
was created as a
JList<String>
) representing the selected items in
colorJList
. We
call the
List<String>
's toArray method to convert this into an array of
String
s that can
be passed as the argument to
copyJList
's
setListData
method.
List
method
toArray
receives as its argument an array representing the type of array that the method will return.
You'll learn more about
List
and
toArray
in Chapter 16.
You might be wondering why
copyJList
can be used in line 42 even though the
application does not create the object to which it refers until line 49. Remember that
method
actionPerformed
(lines 38-45) does not execute until the user presses the
copy-
JButton
, which cannot occur until after the constructor completes execution and the
application displays the GUI. At that point in the application's execution,
copyJList
is
already initialized with a new
JList
object.
This section presents the
MouseListener
and
MouseMotionListener
event-listener inter-
faces for handling
mouse events
. Mouse events can be processed for any GUI component
that derives from
java.awt.Component
. The methods of interfaces
MouseListener
and
MouseMotionListener
are summarized in Figure 12.27. Package
javax.swing.event
contains interface
MouseInputListener
, which extends interfaces
MouseListener
and
MouseMotionListener
to create a single interface containing all the
MouseListener
and
MouseMotionListener
methods. The
MouseListener
and
MouseMotionListener
meth-