repaint() 未在 java 中调用 paintComponent()

repaint() not calling paintComponent() in java

我正在编写应该是一段简单的代码,它创建一个 JFrame 对象,然后将背景涂成黑色并绘制一个蓝色方块。然而,repaint() 方法并没有调用 paintComponent() 方法。

这是代码:

import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Container;

public class Snake extends JPanel{
        private Vector xCoords = new Vector();
        private Vector yCoords = new Vector();

        public Snake(){
                xCoords.add(150);
                yCoords.add(150);
        }

        public void startJFrame(){
                JFrame window = new JFrame();
                window.setSize(300, 300);
                window.setVisible(true);
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                Container c = window.getContentPane();
                c.setBackground(Color.black);
        }

        public void paintRequest(){
                System.out.println("Request to paint received.");
                repaint();
        }

        public void paintComponent(Graphics g){
                super.paintComponent(g);
                System.out.println("paintComponent was called");
                g.setColor(Color.blue);
                int x = (int)xCoords.get(0);
                int y = (int)yCoords.get(0);
                g.fillRect(x, y, 10, 10);
        }

        public static void main(String[] args){
                Snake mkFrame = new Snake();
                mkFrame.startJFrame();
                mkFrame.paintRequest();
        }
}

我知道 paintRequest() 被正确调用,因为它打印 "Request to paint received",但从未打印 "paintComponent was called"。在 gui 端,创建了 JFrame window,它有黑色背景,但没有蓝色方块。预先感谢您的帮助。

没有 Snake 添加到框架中!

变化:

    JFrame window = new JFrame();

收件人:

    JFrame window = new JFrame();
    window.add(new Snake());