本文介绍了面板中的居中字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在面板中居中一个字符串.
I'm trying to center a String in a Panel.
目前我正在这样做:
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
}
}
有没有一种方法可以用来简化这个任务?
Is there a single method I can use to simplify this task?
例如:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (currentMessage.equals(message1)) {
removeAll();
// draw String centered (with one line of code)
}
}
似乎我做了很多工作只是为了使文本居中.
Just seems like I'm doing a lot of work just to center text.
推荐答案
在 java 标准库中?不,你总是可以在这方面做一些事情
In the java standard library? No, you can always do something along this
private void drawStringMiddleOfPanel(String string, Graphics g) {
String message2 = string;
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 */
/** 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();
drawStringMiddleOfPanel(message1, g);
}
}
这篇关于面板中的居中字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!