Moving a Java Swing Rectangle Leaves Rectangles Behind

When I finally figured out the repaint method, I came up with a problem. I want to move the rectangle around the screen, and not re-draw it again. The redraw is beautiful, but there’s an old rectangle behind it! This is my code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Tutorial3{

    public static void main(String[] agrs){
        createAndStartGui();
    }
    static void createAndStartGui(){
        JFrame f = new JFrame("tutorial 3");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setPreferredSize(new Dimension(500, 300));

        MyPanel panel = new MyPanel();
        f.add(panel);

        f.pack();
        f.setVisible(true);

        for (int i = 0; i < 10; i++){
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(Tutorial3.class.getName()).log(Level.SEVERE, null, ex);
            }
            panel.user.move("right");
            panel.repaint();
        }
    }
}

class MyRectangle{
    int x;
    int y;
    public MyRectangle(int x, int y){
        this.x = x;
        this.y = y;
    }
    void move(String direction){
        switch (direction){
            case "up":
                this.y -= 10;
                break;
            case "down":
                this.y += 10;
                break;
            case "left":
                this.x -= 10;
                break;
            case "right":
                this.x += 10;
                break;
            default:
                break;
        }
    }
}

class MyPanel extends JPanel{
    MyRectangle user = new MyRectangle(10, 10);
    public MyPanel(){

    }
    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g.drawRect(user.x, user.y, 10, 10);
    }

}

How to get a disappeared rectangle (I DO NOT WANT TO CLEAN A FULL WINDOW)? Or better yet, how do I get a rectangle to move (if possible)?

My end result:

enter image description here

What I want at the end:

enter image description here

Note: just drawing a rectangle at this point is not what I want. I want to see how he is drawn.

+4
source share
1 answer

, , , , . . "" , , , , . :

super.paintComponent(g);

paintComponent ( - ). , , paintComponent JPanel, .

:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g.drawRect(user.x, user.y, 10, 10);
}

EDIT:

:

, .

, "" . . , . " ...", , . ? . , ? .

( )

. , - . , "", .

, "" , . . paintComponent super.paintComponent(g) , . , , .

, , , , , , super.paintComponent(g) .

paintComponent . . Swing, , .

+9

Source: https://habr.com/ru/post/1544204/


All Articles