java - 面板中的居中字符串

标签 java swing text graphics java-2d

我正在尝试将一个字符串置于面板的中心。

目前我正在这样做:

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)
            }
}

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

最佳答案

尝试类似...

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

相反。

看看Java center text in rectangle更多详情

此外,您可以在带有 GridBagLayoutJPanel 上使用 JLabel 实现相同的效果

已更新

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

更新了示例

并排比较 drawStringJLabel...(左边是 drawString,右边是 JLabel )

enter image description here

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();
        }
    }
}

关于java - 面板中的居中字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18565066/

相关文章:

java - Java/Swing 有哪些好的对接框架?

python - 如何保持python程序运行直到被用户和python文件处理关闭

html - 输入打印时内部没有文本,但在屏幕上可见

java - 找不到 char 的符号

java - 您的 SQL 语法有误; ...在第 1 行的 '[C@f8d6792' 附近

java - 使用 SAX 解析器解析大型 XML 文件(跳过一些行/标签)

ant - 为什么 Ant 在错误的目录中寻找 tools.jar?

java - 如何在JPanel上绘制 "Gantt Chart"?

java - 在 Nimbus Look and Feel 的 JTabbedPane 中将图标左对齐

excel - 如何从具有多种颜色文本的单元格中根据字体颜色提取文本