我使用drawString()
图形绘制字符串的方法,但我想将我的文本居中在一个矩形中。我该怎么做?
问问题
24590 次
2 回答
32
我用它来在 JPanel 上居中文本
Graphics2D g2d = (Graphics2D) g;
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(stringTime, g2d);
int x = (this.getWidth() - (int) r.getWidth()) / 2;
int y = (this.getHeight() - (int) r.getHeight()) / 2 + fm.getAscent();
g.drawString(stringTime, x, y);
于 2013-01-11T19:03:45.020 回答
19
居中文本有很多“选项”。你是绝对居中还是基于基线?
就个人而言,我更喜欢绝对中心位置,但这取决于你在做什么......
public class CenterText {
public static void main(String[] args) {
new CenterText();
}
public CenterText() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int height = getHeight();
String text = "This is a test xyx";
g.setColor(Color.RED);
g.drawLine(0, height / 2, getWidth(), height / 2);
FontMetrics fm = g.getFontMetrics();
int totalWidth = (fm.stringWidth(text) * 2) + 4;
// Baseline
int x = (getWidth() - totalWidth) / 2;
int y = (getHeight() - fm.getHeight()) / 2;
g.setColor(Color.BLACK);
g.drawString(text, x, y + ((fm.getDescent() + fm.getAscent()) / 2));
// Absolute...
x += fm.stringWidth(text) + 2;
y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g.drawString(text, x, y);
}
}
}
于 2013-01-11T21:53:35.137 回答