重绘永远不会到达 paintComponent();

Repaint never reaches paintComponent();

我回来了,有一个关于 java-graphics by swing 的问题...我想在 jframe 上画一些东西,这里是代码:

PaintUtil-class:

public class PaintUtil extends JPanel{

public PaintUtil(){
    this.setFocusable(true);
    this.requestFocus();
}

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        System.out.println("Repainted");

        g.drawstuff...
    }
}

主要-class:

public static PaintUtil util = new PaintUtil();

JFrame frame = new JFrame();
frame.setSize(500,600);
frame.setRezisable(false);
frame.add(util);
frame.setDefaultCloseOperation( 3 );
frame.getContentPane().setColor(Color.BLACK);
setup(); //This add some buttons
frame.setVisible(true);

util.repaint(); //not working
util.paintComponent(frame.getGraphics()); //works

你们能帮帮我吗?

There is no error, no message in the console, just nothing

frame.setLayout(null);

不要使用空布局。 Swing 旨在与布局管理器一起使用。去掉那个语句。

默认情况下,面板的大小为 (0, 0),因此没有可绘制的内容。

您需要重写面板的 getPreferredSize() 方法,以便布局管理器可以完成它的工作。

阅读有关 Custom Painting 的 Swing 教程部分,了解更多信息和工作示例。