我正在尝试在面板中将字符串居中。
目前我正在这样做:
public void paintComponent(Graphics g) {
super.paintComponent(g);
int stringWidth = 0;
int stringAccent = 0;
int xCoordinate = 0;
int yCoordinate = 0;
// get the FontMetrics for the current font
FontMetrics fm = g.getFontMetrics();
/** display new message */
if (currentMessage.equals(message1)) {
removeAll();
/** Centering the text */
// find the center location to display
stringWidth = fm.stringWidth(message2);
stringAccent = fm.getAscent();
// get the position of the leftmost character in the baseline
xCoordinate = getWidth() / 2 - stringWidth / 2;
yCoordinate = getHeight() / 2 + stringAccent / 2;
// draw String
g.drawString(message2, xCoordinate, yCoordinate);
currentMessage = message2; // alternate message
}
}
我可以使用一种方法来简化此任务吗?
例如:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentMessage.equals(message1)) {
removeAll();
// draw String centered (with one line of code)
}
}
似乎我正在做很多工作只是为了使文本居中。