Java drawString是在bounds上面绘制字符串

时间:2012-05-31 19:20:52

标签: java swing jpanel graphics2d drawstring

我有一个Jpanel,例如500宽度和100高度。我有公式来垂直(y)和水平(x)计算屏幕的中心。我使用drawString(myText,x,y),但它将文本写在jpanel的边界之上。这是我正在使用的paintComponent代码。

  protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        String MenuString = Menu.get(MenuChannel);
        fontMetrics = g2d.getFontMetrics(realFont);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setBackground(Color.PINK);
        g2d.fillRect(0,0,getWidth(),getHeight());
        g2d.setColor(Color.WHITE);
        g2d.setFont(realFont);

        java.awt.geom.Rectangle2D rect = fontMetrics.getStringBounds(MenuString, g2d);
        int textHeight = (int)rect.getHeight();
        int textWidth = (int)rect.getWidth();
        int panelHeight = getHeight();
        int panelWidth = getWidth();
        int x = (panelWidth - textWidth) / 2;
        int y = (panelHeight - textHeight) / 2;
        System.out.println("tH:" + textHeight + "\ntW:" + textWidth + "\npH:" + panelHeight + "\npW:" + panelWidth);
        g2d.drawString(MenuString,x,y);
}

1 个答案:

答案 0 :(得分:3)

是的 - 这很痛苦 - drawString会使用String作为底线(或基本文字行)来绘制y。如果你想在String中居中String,你应该使用FontMetrics

来实现它