我正在尝试在我的JFrame窗口中间绘制文本,并且稍微关闭了。
这是我尝试过的:
FontMetrics fontMetrics = g.getFontMetrics(font);
// draw title
g.setColor(Color.WHITE);
g.setFont(font);
int titleLen = fontMetrics.stringWidth("Level 1 Over!");
g.drawString("Level 1 Over!", (screenWidth / 2) - (titleLen / 2), 80);
答案 0 :(得分:3)
我发现TextLayout类为String提供了比FontMetrics更好的维度。
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (font == null) {
return;
}
Graphics2D g2d = (Graphics2D) g;
FontRenderContext frc = g2d.getFontRenderContext();
TextLayout layout = new TextLayout(sampleString, font, frc);
Rectangle2D bounds = layout.getBounds();
int width = (int) Math.round(bounds.getWidth());
int height = (int) Math.round(bounds.getHeight());
int x = (getWidth() - width) / 2;
int y = height + (getHeight() - height) / 2;
layout.draw(g2d, (float) x, (float) y);
}
答案 1 :(得分:2)
使用您的代码,String从中间开始。试试这个:
FontMetrics fontMetrics = g.getFontMetrics(font);
// draw title
g.setColor(Color.WHITE);
g.setFont(font);
int titleLen = fontMetrics.stringWidth("Level 1 Over!");
g.drawString("Level 1 Over!", (screenWidth / 2) - (titleLen), 80);
答案 2 :(得分:1)
我知道这已经过时但这对我有用......
public void drawCenter ( String m , Font font )
FontMetrics fm = g.getFontMetrics ( font );
int sw = fm.stringWidth ( m );
g.setFont ( font );
g.setColor ( Color.BLACK );
g.drawString ( m , ( frame.getWidth() + sw ) / 2 - sw , frame.getHeight() / 2 );
}
在这个例子中,g是Graphics2D,但我认为它也适用于Graphics
答案 3 :(得分:0)
- 使用Toolkit
获取屏幕的高度和宽度。
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
- 然后在屏幕中间设置文字。
g.drawString("Level 1 Over!",(width/2),(height/2));