调用repaint()时字符串字体大小更小

时间:2014-08-05 21:22:49

标签: java paint font-size

当我用g.drawString()绘制字符串时,生成的文本小于设置的字体。如果您运行以下代码,您可以看到显示所需的字体大小,然后在第二个线程调用repaint()之后显示较小的字体大小我在调用SwingUtilities.invokeLater()之前尝试了repaint但是这没有帮助。有什么想法吗?

import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {
    static JPanel   panel;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        panel = new JPanel() {
            private static final long   serialVersionUID    = 1L;

            public void paint(Graphics g) {
                g.clearRect(0, 0, panel.getWidth(), panel.getHeight());
                g.drawString("TEST", 20, 100);// Where I draw the string
            }
        };
        panel.setFont(new Font("Arial", Font.BOLD, 30));// The desired font
        frame.add(panel);
        frame.setSize(500, 500);
        frame.setVisible(true);
        new Thread() {// This thread calls repaint() after two seconds
            public void run() {
                try {
                    Thread.sleep(2000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                panel.repaint();
            }
        }.start();
    }
}

2 个答案:

答案 0 :(得分:6)

  1. 不要覆盖绘画,而是覆盖paintComponent。
  2. 始终调用超级方法。

  3. e.g。

      panel = new JPanel() {
         private static final long serialVersionUID = 1L;
    
         @Override
         protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // g.clearRect(0, 0, panel.getWidth(), panel.getHeight());
            g.drawString("TEST", 20, 100);// Where I draw the string
         }
      };
    

答案 1 :(得分:4)

问题是,paint可能设置要使用的字体,然后再绘制组件的重置,因为您已覆盖它,但未能调用super.paint,它有没有机会设定这些值

而不是覆盖paint,而是覆盖paintComponent而不是......

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("TEST", 20, 100);// Where I draw the string
}

绘画是一系列链式方法调用的复杂过程,如果你打破这个链条,为一些严重的怪异做好准备

请查看Performing Custom PaintingPainting in AWT and Swing了解详情