Javax.swing 如何删除之前的矩形

Javax.swing How to delete previous rectangle

如何删除之前绘制的矩形? 我是 javax.swing 和 java.awt 库领域的初学者,我看了很多教程甚至 java 文档,但似乎没有任何效果

public class Main extends javax.swing.JFrame implements KeyListener {
    private Rectangle player;
    private int playerX = 50;
    private int playerY = 50;
    public static void main(String[] args) {
        Main main = new Main();
        main.setSize(400, 400);
        main.setVisible(true);
    }
    public Main() {
        this.addKeyListener(this);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                e.getWindow().dispose();
            }
        });
        this.player = new Rectangle(this.playerX, this.playerY, 100, 100);
    }
    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                this.player.setLocation(this.player.x - 10, this.player.y);
                break;
            case KeyEvent.VK_RIGHT:
                this.player.setLocation(this.player.x + 10, this.player.y);
                break;
            case KeyEvent.VK_UP:
                this.player.setLocation(this.player.x, this.player.y - 10);
                break;
            case KeyEvent.VK_DOWN:
                this.player.setLocation(this.player.x, this.player.y + 10);
                break;
            default : break;
        }
        this.repaint();
    }
    @Override
    public void paint(java.awt.Graphics g) {
        g.drawRect(this.player.x, this.player.y, 100, 100);
    }
}

你必须像这样在方法paint中调用超级方法:

@Override
public void paint(java.awt.Graphics g) {
    super.paint(g);
    g.drawRect(this.player.x, this.player.y, 100, 100);
}

或者您也可以自己进行清理,方法是在 JFrame 中绘制一个填充的矩形。

使用 canvas 会很有用。