简体   繁体   中英

Javax.swing How to delete previous rectangle

How can I delete previous drew rectangle? I'm begginer in field of javax.swing and java.awt library, I watched numerous tutorials even java documentation , but nothing seems to work

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);
    }
}

You have to call the super method in the method paint like this:

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

Or you can perform the cleanup yourself too by drawing a filled rectangle in your JFrame .

Using a canvas can be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM