Java Reference
In-Depth Information
ImageIcon objects that represent the default Icon and rollover Icon for the JButton cre-
ated at line 28. Both statements assume that the image files are stored in the same directory
as the application. Images are commonly placed in the same directory as the application or
a subdirectory like images ). These image files have been provided for you with the
example.
Line 28 creates fancyButton with the text "Fancy Button" and the icon bug1 . By
default, the text is displayed to the right of the icon. Line 29 uses setRolloverIcon (inher-
ited from class AbstractButton ) to specify the image displayed on the JButton when the
user positions the mouse over it. Line 30 adds the JButton to the JFrame .
Look-and-Feel Observation 12.10
Because class AbstractButton supports displaying text and images on a button, all sub-
classes of AbstractButton also support displaying text and images.
Look-and-Feel Observation 12.11
Rollover icons provide visual feedback indicating that an action will occur when when a
JButton is clicked.
JButton s, like JTextField s, generate ActionEvent s that can be processed by any
ActionListener object. Lines 33-35 create an object of private inner class ButtonHan-
dler and use addActionListener to register it as the event handler for each JButton . Class
ButtonHandler (lines 39-48) declares actionPerformed to display a message dialog box
containing the label for the button the user pressed. For a JButton event, ActionEvent
method getActionCommand returns the label on the JButton .
Accessing the this Reference in an Object of a Top-Level Class from an Inner Class
When you execute this application and click one of its buttons, notice that the message
dialog that appears is centered over the application's window. This occurs because the call
to JOptionPane method showMessageDialog (lines 45-46) uses ButtonFrame.this rather
than null as the first argument. When this argument is not null , it represents the so-called
parent GUI component of the message dialog (in this case the application window is the
parent component) and enables the dialog to be centered over that component when the
dialog is displayed. ButtonFrame.this represents the this reference of the object of top-
level class ButtonFrame .
Software Engineering Observation 12.2
When used in an inner class, keyword this refers to the current inner-class object being
manipulated. An inner-class method can use its outer-class object's this by preceding this
with the outer-class name and a dot ( . ) separator, as in ButtonFrame.this .
12.10 Buttons That Maintain State
The Swing GUI components contain three types of state buttons JToggleButton ,
JCheckBox and JRadioButton —that have on/off or true/false values. Classes JCheckBox
and JRadioButton are subclasses of JToggleButton (Fig. 12.14). A JRadioButton is dif-
ferent from a JCheckBox in that normally several JRadioButton s are grouped together and
 
 
Search WWH ::




Custom Search