Java Reference
In-Depth Information
}
}
Drawing Centered Text in a Component
Problem
You want to draw text neatly centered in a component.
Solution
Measure the width and height of the string in the given font, and subtract it from the width
and height of the component. Divide by two, and use this as your drawing location.
Discussion
(see
Figure 12-2
for some attributes of the text). The program then subtracts the size of the
text from the size of the component, divides this by two, and thereby centers the text in the
given component.
Example 12-1. DrawStringDemo2.java
public
public class
class
DrawStringDemo2
DrawStringDemo2
extends
extends
JComponent
{
private
private static
static final
final
long
long
serialVersionUID
= -
6593901790809089107L
;
//-
String message
=
"Hello Java"
;
/** Called by the window system to draw the text. */
@Override
public
public
void
void
paintComponent
(
Graphics g
) {
// Get the current Font, and ask it for its FontMetrics.
FontMetrics fm
=
getFontMetrics
(
getFont
());
// Use the FontMetrics to get the width of the String.
// Subtract this from width, divide by 2, that's our starting point.
int
int
textX
= (
getSize
().
width
-
fm
.
stringWidth
(
message
))/
2
;
iif
(
textX
<
0
)
// If string too long, start at 0
textX
=
0
;