JPanel 中未调用 paintComponent

paintComponent is not being called in JPanel

我有以下代码:

package hra;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class HerniPole extends JPanel implements KeyListener
{
    public int velikostPole;
    HerniPole(int velikostPole)
    {
        this.velikostPole = velikostPole;

        Color background = new Color(187, 173, 163);
        EventQueue.invokeLater(new Runnable() 
        {
            @Override
            public void run() 
            {
                try 
                {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
                {
                    System.err.println("Error!");
                }
            }
        });
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setTitle("2048");
        frame.getContentPane().setBackground(background);
        frame.setSize(450, 450);
        frame.addKeyListener(this);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    @Override
    public void paintComponent(Graphics g)
    {
        System.out.println("xD");
        g.setColor(Color.BLACK);
        g.drawRect(20, 20, 20, 20);
        g.setColor(Color.yellow);
    }

    @Override
    public void keyTyped(KeyEvent ke) 
    {
        System.out.println(ke.getKeyCode());
    }
    @Override
    public void keyPressed(KeyEvent ke) 
    {

    }
    @Override
    public void keyReleased(KeyEvent ke) 
    {

    }
}

并且没有调用 paintComponent(),也没有调用 paint() 甚至 repaint()。我究竟做错了什么?我已经尝试了在 Whosebug 上找到的所有内容,但没有任何效果。如何解决?谢谢

你错过了一些东西:

您没有 main 方法(或者在您的问题中您可能有但没有 post)并且从未创建过 HerniPole 实例。 添加一个 main 方法,如下所示:

public static void main(String[] args) {
    new HerniPole(0);
}

您没有将 HerniPole 实例添加到 JFrame。 在构造函数中,在 frame.setVisible(true);

之前的某处执行此操作
 frame.add(this);