为什么没有调用 paint?

Why is paint not being called?

我用三种方法创建了一个 class。我最初从稍微不同的编码开始,在看了几个视频和问题后改变了它,直到我结束了这个。出于某种原因,我试图制作的正方形根本不会出现在我的屏幕上。请提出您的任何建议。我是最近才开始的,我敢肯定这是显而易见的。请原谅我犯的任何常规错误。作为旁注,我发现问题是方法 "paint" 没有被调用。由于我是新手,在尝试了几种不同的方法后,我不知道如何称呼它。如果您对我的代码有任何澄清问题,请询问。谢谢!

public class TheGame extends JPanel {

public void screen() {
    JFrame f = new JFrame();
    f.setTitle("Grid Game");
    f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setBounds(250, 250, 500, 500);
    f.add(this);
    f.setVisible(true);
}

public void paint(Graphics2D g) {
    g.setColor(Color.BLACK);
    g.fillRect(50, 50, 200, 200);

}

public static void main(String[] args) {
    TheGame game = new TheGame();
    game.screen();
}

您需要override paintComponent() 方法:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(50, 50, 200, 200);
}