1

我正在尝试在面板中将字符串居中。

目前我正在这样做:

public void paintComponent(Graphics g) {
        super.paintComponent(g);
            int stringWidth = 0;
            int stringAccent = 0;
            int xCoordinate = 0;
            int yCoordinate = 0;
            // get the FontMetrics for the current font
            FontMetrics fm = g.getFontMetrics();


        /** display new message */
        if (currentMessage.equals(message1)) {
            removeAll();
            /** Centering the text */
            // find the center location to display
            stringWidth = fm.stringWidth(message2);
            stringAccent = fm.getAscent();
            // get the position of the leftmost character in the baseline
            xCoordinate = getWidth() / 2 - stringWidth / 2;
            yCoordinate = getHeight() / 2 + stringAccent / 2;

            // draw String
            g.drawString(message2, xCoordinate, yCoordinate);
            currentMessage = message2;  // alternate message
        }
}

我可以使用一种方法来简化此任务吗?

例如:

public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (currentMessage.equals(message1)) {
                removeAll();
                // draw String centered (with one line of code)
            }
}

似乎我正在做很多工作只是为了使文本居中。

4

3 回答 3

5

尝试类似...

xCoordinate = (getWidth() - stringWidth) / 2;
yCoordinate = ((getHeight() - fm.getHeight) / 2) + stringAccent;

反而。

查看矩形中的 Java 中心文本以获取更多详细信息

JLabel此外,您可以使用aJPanel和 a来实现相同的目的GridBagLayout

更新

刚刚注意到removeAll();paintComponent. 这不是一个好主意,因为它可能会导致将新的重绘请求发布到事件队列,从而将您的代码放入可能消耗 CPU 的无限循环中......

更新了示例

并排比较drawStringJLabel...(drawString在左侧,JLabel在右侧)

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

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("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(1, 2));
                frame.add(new CenterStringPane());
                frame.add(new CenterLabelPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class CenterStringPane extends ReferencePane {

        public CenterStringPane() {
            setFont(UIManager.getFont("Label.font"));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            String text = "In the center";
            FontMetrics fm = g2d.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();

            g2d.drawString(text, x, y);

            g2d.dispose();
        }
    }

    public class CenterLabelPane extends ReferencePane {

        public CenterLabelPane() {

            setLayout(new GridBagLayout());
            add(new JLabel("In the center"));

        }
    }

    public class ReferencePane extends JPanel {

        public ReferencePane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int halfX = getWidth() / 2;
            int halfY = getHeight() / 2;
            g2d.drawLine(halfX, 0, halfX, getHeight());
            g2d.drawLine(0, halfY, getWidth(), halfY);
            g2d.dispose();
        }
    }
}
于 2013-09-02T03:02:40.560 回答
3

在java标准库中?不,你总是可以做一些事情

private void drawStringMiddleOfPanel(String string, Graphics g) {
            String message2 = string;
            int stringWidth = 0;
            int stringAccent = 0;
            int xCoordinate = 0;
            int yCoordinate = 0;
            // get the FontMetrics for the current font
            FontMetrics fm = g.getFontMetrics();


        /** display new message */
            /** Centering the text */
            // find the center location to display
            stringWidth = fm.stringWidth(message2);
            stringAccent = fm.getAscent();
            // get the position of the leftmost character in the baseline
            xCoordinate = getWidth() / 2 - stringWidth / 2;
            yCoordinate = getHeight() / 2 + stringAccent / 2;

            // draw String
            g.drawString(message2, xCoordinate, yCoordinate);
            currentMessage = message2;  // alternate message
        }

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (currentMessage.equals(message1)) {
            removeAll();
            drawStringMiddleOfPanel(message1, g);
        }
 }
于 2013-09-02T03:04:53.797 回答
1
   public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (currentMessage.equals(message1)) {
            removeAll();
            int x=  (panel.getWidth() / 2) - str.length()/2;
            int y = (panel.getHeight() / 2);
            graphics.drawString(str, x, y);

        }
   }
于 2013-09-02T03:08:11.310 回答