Java Reference
In-Depth Information
The application of Figs. 12.15 and 12.16 creates two
JButton
s and demonstrates that
JButton
s can display
Icon
s. Event handling for the buttons is performed by a single
instance of
inner class
ButtonHandler
(Fig. 12.15, lines 39-48).
1
// Fig. 12.15: ButtonFrame.java
2
// Command buttons and action events.
3
import
java.awt.FlowLayout;
4
import
java.awt.event.ActionListener;
5
import
java.awt.event.ActionEvent;
6
import
javax.swing.JFrame;
7
import
javax.swing.JButton;
8
import
javax.swing.Icon;
9
import
javax.swing.ImageIcon;
10
import
javax.swing.JOptionPane;
11
12
public
class
ButtonFrame
extends
JFrame
13
{
14
private final
JButton plainJButton;
// button with just text
private final
JButton fancyJButton;
// button with icons
15
16
17
// ButtonFrame adds JButtons to JFrame
18
public
ButtonFrame()
19
{
20
super
(
"Testing Buttons"
);
21
setLayout(new FlowLayout());
22
23
plainJButton =
new
JButton(
"Plain Button"
);
// button with text
24
add(plainJButton);
// add plainJButton to JFrame
25
26
Icon bug1 =
new
ImageIcon(getClass().getResource(
"bug1.gif"
));
Icon bug2 =
new
ImageIcon(getClass().getResource(
"bug2.gif"
));
fancyJButton =
new
JButton(
"Fancy Button"
, bug1);
// set image
fancyJButton.setRolloverIcon(bug2);
// set rollover image
27
28
29
30
add(fancyJButton);
// add fancyJButton to JFrame
31
32
// create new ButtonHandler for button event handling
ButtonHandler handler =
new
ButtonHandler();
fancyJButton.addActionListener(handler);
plainJButton.addActionListener(handler);
33
34
35
36
}
37
38
// inner class for button event handling
39
private
class
ButtonHandler
implements
ActionListener
40
{
41
// handle button event
42
@Override
43
public
void
actionPerformed(ActionEvent event)
44
{
45
JOptionPane.showMessageDialog(
ButtonFrame.
this
event.getActionCommand()
, String.format(
46
"You pressed: %s"
,
));
47
}
48
}
49
}
// end class ButtonFrame
Fig. 12.15
|
Command buttons and action events.