Java Reference
In-Depth Information
// Same as above but for the height
int
int
textY
= (
getSize
().
height
-
fm
.
getAscent
())/
2
-
fm
.
getDescent
();
iif
(
textY
<
0
)
textY
=
getSize
().
height
-
fm
.
getDescent
() -
1
;
// Now draw the text at the computed spot.
g
.
drawString
(
message
,
textX
,
textY
);
}
//-
public
public
Dimension
getPreferredSize
() {
return
return new
new
Dimension
(
100
,
100
);
}
public
public static
static
void
void
main
(
final
final
String
[]
args
) {
final
final
JFrame jf
=
new
new
JFrame
();
jf
.
add
(
new
new
DrawStringDemo2
());
jf
.
setBounds
(
100
,
100
,
100
,
100
);
jf
.
setVisible
(
true
true
);
}
}
Figure 12-2. Font metrics
This is so common that you'd expect Java to have encapsulated the whole thing as a service,
and in fact, Java does do this. What we have here is what most GUI component architectures
centered (or left- or right-aligned) text and supports the setting of fonts and colors. It also of-
fers
JLabel
, which provides image icons in addition to or instead of text.