Java Reference
In-Depth Information
You can set a border for any object of the
JComponent
class. Swing has several types of
borders. To create a titled border, use
new TitledBorder(String title)
. To create a
line border, use
new LineBorder(Color color, int width)
, where
width
specifies
the thickness of the line.
Listing 12.7 is an example to demonstrate Swing common features. The example creates a
panel
p1
to hold three buttons (line 8) and a panel
p2
to hold two labels (line 26), as shown in
Figure 12.12. The background of the button
jbtLeft
is set to white (line 12) and the fore-
ground of the button
jbtCenter
is set to green (line 13). The tool tip of the button
jbtRight
is set in line 14. Titled borders are set on panels
p1
and
p2
(lines 18, 37) and line borders are
set on the labels (lines 33-34).
border
Cross-hair cursor
Titled border
Having the mouse cursor
over the Right button
displays the tool tip text
Titled border
Line border
F
IGURE
12.12
The font, color, border, and tool tip text are set in the message panel.
The mouse cursor is set to the cross-hair shape in
p1
(line 19). The
Cursor
class contains
the constants for specifying the cursor shape such as
DEFAULT_CURSOR
( ),
CROSSHAIR_CURSOR
( ),
HAND_CURSOR
( ),
MOVE_CURSOR
( ),
TEXT_CURSOR
( ,
and so on. A
Cursor
object for the cross-hair cursor is created using
new
Cursor(Cursor.CROSSHAIR_CURSOR)
(line 19) and this cursor is set for
p1
. Note that the
default mouse cursor is still used in
p2
, because the program does not explicitly set a mouse
cursor for
p2
.
mouse cursor
L
ISTING
12.7
TestSwingCommonFeatures.java
1
import
java.awt.*;
2
import
javax.swing.*;
3
import
javax.swing.border.*;
4
5
public class
TestSwingCommonFeatures
extends
JFrame {
6
public
TestSwingCommonFeatures() {
7
// Create a panel to group three buttons
8 JPanel p1 =
new
JPanel(
new
FlowLayout(FlowLayout.LEFT,
2
,
2
));
9 JButton jbtLeft =
new
JButton(
"Left"
);
10 JButton jbtCenter =
new
JButton(
"Center"
);
11 JButton jbtRight =
new
JButton(
"Right"
);
12
13
14
15 p1.add(jbtLeft);
16 p1.add(jbtCenter);
17 p1.add(jbtRight);
18
19
20
21
jbtLeft.setBackground(Color.WHITE);
set background
set foreground
set tool tip text
jbtCenter.setForeground(Color.GREEN);
jbtRight.setToolTipText(
"This is the Right button"
);
p1.setBorder(
new
TitledBorder(
"Three Buttons"
));
set titled border
set mouse cursor
p1.setCursor(
new
Cursor(Cursor.CROSSHAIR_CURSOR));
// Create a font and a line border
22
23
Font largeFont =
new
Font(
"TimesRoman"
, Font.BOLD,
20
);
create a font
create a border
Border lineBorder =
new
LineBorder(Color.BLACK,
2
);