0

My issue here with ball animation is that the ball is moving in a straight line leaving behind a trail. My expected output is that there should be no trail of the ball.

The code determines the movement of the ball in just one direction along X axis.

public class App extends JFrame implements Runnable{

    int x=0,y=250;

    public void run() {
      for(;;) {
        try {
          repaint();
          x++;
          Thread.sleep(10);
        } catch(Exception e){}
      }
    }

    public void paint(Graphics g) { 
      g.drawOval(x,y,30,30);
    }

    public static void main(String[] args) {
        App frame= new App();
        frame.setTitle("Bounce");
        frame.setSize(400, 450);
        frame.setVisible(true);
        Thread t1 = new Thread(frame);
        t1.start();
    }
}
jolivier
  • 7,380
  • 3
  • 29
  • 47
Prinze
  • 1
  • 1
  • [Drawing a rectangle that won't disappear in next paint](http://stackoverflow.com/questions/12683533/drawing-a-rectangle-that-wont-disappear-in-next-paint) Should go over what your problem is and how to fix it. You need to use `paintComponent(Graphics g)` and call `super.paintComponent(g)` to get rid of that "trail". – Obicere Mar 29 '17 at 20:14
  • Ouch. This is very bad approach in general. Whole GUI runs outside of EDT. – Branislav Lazic Mar 29 '17 at 20:18

2 Answers2

0

You missed to call super.paint in your paint method:

public void paint(Graphics g) {
  super.paint(g);
  g.drawOval(x,y,30,30);
}
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
0

This is not a multi-threading issue, you just never "erase" the ovals you draw for the previous x. Your paint method needs to call super.paint() in order to clear the previous ovals. This is explained here with almost the same code as you but without your issue!

jolivier
  • 7,380
  • 3
  • 29
  • 47