【发布时间】:2013-09-05 01:57:24
【问题描述】:
我正在尝试在面板中将字符串居中。
目前我正在这样做:
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)
}
}
似乎我做了很多工作只是为了使文本居中。
【问题讨论】:
-
将文本放入标签“更简单”,因为标签会返回首选大小。如
LabelRenderTest所示。为了尽快获得更好的帮助,请发帖SSCCE。
标签: java swing text graphics java-2d