Java Reference
In-Depth Information
after
new
begins the declaration of an anonymous inner class that implements interface
ItemListener
. This is similar to beginning a class declaration with
public class
MyHandler
implements
ItemListener
The opening left brace at line 36 and the closing right brace at line 46 delimit the
body of the anonymous inner class. Lines 38-45 declare the
ItemListener
's
itemState-
Changed
method. When the user makes a selection from
imagesJComboBox
, this method
sets
label
's
Icon
. The
Icon
is selected from array
icons
by determining the index of the
selected item in the
JComboBox
with method
getSelectedIndex
in line 44. For each item
selected from a
JComboBox
, another item is first deselected—so two
ItemEvent
s occur
when an item is selected. We wish to display only the icon for the item the user just
selected. For this reason, line 42 determines whether
ItemEvent
method
getStateChange
returns
ItemEvent.SELECTED
. If so, lines 43-44 set
label
's icon.
Software Engineering Observation 12.4
Like any other class, when an anonymous inner class implements an interface, the class
must implement every
abstract
method in the interface.
The syntax shown in lines 35-46 for creating an event handler with an anonymous
inner class is similar to the code that would be generated by a Java integrated development
environment (IDE). Typically, an IDE enables you to design a GUI visually, then it gen-
erates code that implements the GUI. You simply insert statements in the event-handling
methods that declare how to handle each event.
Java SE 8: Implementing Anonymous Inner Classes with Lambdas
In Section 17.9, we show how to use Java SE 8 lambdas to create event handlers. As you'll
learn, the compiler translates a lambda into an object of an anonymous inner class.
A list displays a series of items from which the user may
select one or more items
(see the output
of Fig. 12.24). Lists are created with class
JList
, which directly extends class
JComponent
.
Class
JList
—which like
JComboBox
is a generic class—supports
single-selection lists
(which
allow only one item to be selected at a time) and
multiple-selection lists
(which allow any
number of items to be selected). In this section, we discuss single-selection lists.
The application of Figs. 12.23-12.24 creates a
JList
containing 13 color names.
When a color name is clicked in the
JList
, a
ListSelectionEvent
occurs and the appli-
cation changes the background color of the application window to the selected color. Class
ListTest
(Fig. 12.24) contains the
main
method that executes this application.
1
// Fig. 12.23: ListFrame.java
2
// JList that displays a list of colors.
3
import
java.awt.FlowLayout;
4
import
java.awt.Color;
5
import
javax.swing.JFrame;
6
import
javax.swing.JList;
Fig. 12.23
|
JList
that displays a list of colors. (Part 1 of 2.)