2

I'm trying to draw text in the middle of my JFrame window, and it's off by a little bit.

Here's what I've tried :

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);
4

4 回答 4

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);
}
于 2013-08-28T12:40:36.247 回答
2

使用您的代码,字符串从中间开始。尝试这个:

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);
于 2013-08-28T09:15:19.383 回答
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

于 2014-10-04T20:00:19.990 回答
0

-用于Toolkit获取屏幕的高度宽度

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

-然后将文本设置在屏幕中间。

g.drawString("Level 1 Over!",(width/2),(height/2));
于 2013-08-28T09:22:27.427 回答