1

たとえば、幅500、高さ100のJpanelがあります。画面の中心を垂直方向 (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);
}
4

1 に答える 1

3

はい - これは苦痛です -最終行 (またはベース テキスト行) として使用してdrawString描画します。String を Rectangle の中央に配置する場合は、次を使用して実装する必要がありますStringyFontMetrics

于 2012-05-31T19:23:59.463 に答える