Java Reference
In-Depth Information
This method returns the font metrics of the current font.
You can use the following instance methods in the
FontMetrics
class to obtain the attributes
of a font and the width of a string when it is drawn using the font:
public int
getAscent()
// Return the ascent
public int
getDescent()
// Return the descent
public int
getLeading()
// Return the leading
public int
getHeight()
// Return the height
public int
stringWidth(String str)
// Return the width of the string
Listing 13.6 gives an example that displays a message in the center of the panel, as shown in
Figure 13.17.
L
ISTING
13.6
TestCenterMessage.java
1
import
javax.swing.*;
2
import
java.awt.*;
3
4
public class
TestCenterMessage
extends
JFrame {
5
public
TestCenterMessage() {
6 CenterMessage messagePanel =
new
CenterMessage();
7 add(messagePanel);
8 messagePanel.setBackground(Color.WHITE);
9 messagePanel.setFont(
new
Font(
"Californian FB"
, Font.BOLD,
30
));
10 }
11
12
/** Main method */
13
public static void
main(String[] args) {
14 TestCenterMessage frame =
new
TestCenterMessage();
15 frame.setSize(
300
,
150
);
16 frame.setTitle(
"CenterMessage"
);
17 frame.setLocationRelativeTo(
null
);
// Center the frame
18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19 frame.setVisible(
true
);
20 }
21 }
22
23
class
CenterMessage
extends
JPanel {
24 @Override
/** Paint the message */
25
create a message panel
add a message panel
set background
set font
protected void
paintComponent(Graphics g) {
override
paintComponent
26
super
.paintComponent(g);
27
28
// Get font metrics for the current font
FontMetrics fm = g.getFontMetrics();
get
FontMetrics
29
30
31
// Find the center location to display
32
int
stringWidth =
fm.stringWidth(
"Welcome to Java"
)
;
33
int
stringAscent =
fm.getAscent()
;
34
35
// Get the position of the leftmost character in the baseline
36
int
xCoordinate = getWidth() /
2
- stringWidth /
2
;
37
int
yCoordinate = getHeight() /
2
+ stringAscent /
2
;
38
39
40 }
41 }
g.drawString(
"Welcome to Java"
, xCoordinate, yCoordinate);