有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

图形如何在Java中绘制文本上方的线

我想在Java文本上方画一条线。我使用图形,以下是我的代码:

String s = a.getSequent().toString();
FontMetrics fm = getFontMetrics(getFont());
int textHeight = fm.getHeight();
int textWidth= fm.stringWidth(s);

//Text
g.drawString( s,
        (int) ((jPanelWidth- textWidth) / 2),
        (int) ((jPanelHeight- textHeight ) / 2));

//Draw line
int x1 = (jPanelWidth- textWidth) / 2;
int x2 = x1 + textWidth; //Problem
int y1 = (jPanelHeight- textHeight *4) / 2;
int y2 = y1;
g.drawLine(x1, y1, x2, y2);

以下是我所拥有的:

enter image description here

我不明白为什么这行的长度和我的文本不一样。问题在于x2的值,但为什么?你能帮我吗


共 (2) 个答案

  1. # 1 楼答案

    正如@luk2302所说,解决方案如下:

    我有:FontMetrics fm = getFontMetrics(getFont());

    现在我有:FontMetrics fm = getFontMetrics(g.getFont());

    我没有使用正确的字体

  2. # 2 楼答案

    其中一个比较模糊的概念是理解文本实际上是如何呈现的

    文本不是从x/y位置向下渲染,而是从基线向上渲染

    Text baseline

    这意味着x/y位置实际上代表基线。。。只要花点时间再读一遍,如果没有帮助,就读一读Measuring Text

    基本的概念是,你需要取x/y位置,它代表基线,然后减去上升

    For example

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
    
                Graphics2D g2d = (Graphics2D) g.create();
    
                g2d.setColor(Color.RED);
                g2d.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
                g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
    
                String text = "This is a test";
                FontMetrics fm = g2d.getFontMetrics();
    
                int textHeight = fm.getHeight();
                int textWidth = fm.stringWidth(text);
    
                int xPos = (getWidth() - textWidth) / 2;
                int yPos = ((getHeight() - textHeight) / 2) + fm.getAscent();
    
                g2d.setColor(Color.BLACK);
                g2d.drawString(text, xPos, yPos);
    
                g2d.drawLine(xPos, yPos - fm.getAscent(), xPos + textWidth, yPos - fm.getAscent());
    
                g2d.dispose();
            }
    
        }
    }