Java Reference
In-Depth Information
JButton
inherits
AbstractButton
and provides several constructors to create buttons,
as shown in Figure 12.16.
javax.swing.AbstractButton
javax.swing.JButton
+JButton()
+JButton(icon: javax.swing.Icon)
+JButton(text: String)
+JButton(text: String, icon: Icon)
Creates a default button without any text or icons.
Creates a button with an icon.
Creates a button with text.
Creates a button with text and an icon.
F
IGURE
12.16
JButton
defines a regular push button.
12.11.1 Icons, Pressed Icons, and Rollover Icons
A button has a default icon, a pressed icon, and a rollover icon. Normally you use the
default icon, because the other icons are for special effects. A pressed icon is displayed
when a button is pressed, and a rollover icon is displayed when the mouse is over the but-
ton but not pressed. For example, Listing 12.9 displays the U.S. flag as a regular icon,
the Canadian flag as a pressed icon, and the British flag as a rollover icon, as shown in
Figure 12.17.
L
ISTING
12.9
TestButtonIcons.java
1
import
javax.swing.*;
2
3
public class
TestButtonIcons
extends
JFrame {
4
public static void
main(String[] args) {
5
// Create a frame and set its properties
6 JFrame frame =
new
TestButtonIcons();
7 frame.setTitle(
"ButtonIcons"
);
8 frame.setSize(
200
,
100
);
9 frame.setLocationRelativeTo(
null
);
// Center the frame
10 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11 frame.setVisible(
true
);
12 }
13
14
public
TestButtonIcons() {
15 ImageIcon usIcon =
new
ImageIcon(
"image/usIcon.gif"
);
16 ImageIcon caIcon =
new
ImageIcon(
"image/caIcon.gif"
);
17 ImageIcon ukIcon =
new
ImageIcon(
"image/ukIcon.gif"
);
18
19 JButton jbt =
new
JButton(
"Click it"
, usIcon);
20 jbt.setPressedIcon(caIcon);
21 jbt.setRolloverIcon(ukIcon);
22
23 add(jbt);
24 }
25 }
create icons
regular icon
pressed icon
rollover icon
add a button
(a) Default icon
(b) Pressed icon
(c) Rollover icon
F
IGURE
12.17
A button can have several types of icons.