Hello. I apologize in advance for a stupid question. So, I master Swing, trying to draw an animated figure on jpanel. The figure is drawn, but not redrawn, i.e. instead of moving the coordinates of the circle, each time a new circle is drawn with the changed coordinates, and the old one remains on the panel. Here is the code:

public class Frame extends JFrame { public Frame() { super("MOON>MOONS"); initComponents(); timer.start(); } private void initComponents() { JPanel panel = new JPanel(); getContentPane().add(panel); initBalls(); } private void initBalls() { Random random = new Random(); for(int i = 0; i < 7; i++) { Ball ball = new Ball(random.nextInt(200), 200); Ball.balls.add(ball); } } public void paint(Graphics g) { for (Ball ball : Ball.balls) { g.drawOval(ball.getX(), ball.getY(), 60, 60); } } Timer timer = new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (Ball ball : Ball.balls) { ball.move(ball); repaint(); } } }); } public class Ball { private int x; private int y; public static List<Ball> balls = new ArrayList<>(); public Ball(int x, int y) { this.x = x; this.y = y; } public void addBall(Ball b) { balls.add(b); } public void removeBall(Ball b) { balls.remove(b); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void move(Ball ball) { ball.setX(x+1); ball.setY(y+1); } } 

    1 answer 1

    You need to clear the screen to erase the old figure.

    Use:

     g.clearRect(0, 0, width, height); 
    • Thank you very much! It helped. - lounah