4

I am trying to make a simple ball animation, that starts from 1 corner and goes to another corner of the panel. I have written a program for that.

When I run the program the oval or ball leaves the trail. What I mean to say is that it leaves it's 'color trail' when the program runs. In my program timer fires an event every 100 milliseconds.

The following is the logic responsible for running the code :

void function() {
  // in this there is a action listener timed accordingly to fire event of 
  // doing x++ every 100th miliseconds
}

public void paintComponent(final Graphics g) {
 g.setColor(Color.black);
 g.drawOval(x,y,width,height);
 g.fillOval(x,y,width,height);
}

Screen shot of the output :

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
saplingPro
  • 20,769
  • 53
  • 137
  • 195

1 Answers1

6

Try

public void paintComponent(final Graphics g) {
 super.paintComponent(g);

 g.setColor(Color.black);
 g.drawOval(x,y,width,height);
 g.fillOval(x,y,width,height);
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • @ Bala R yes that works.But what is the role of `super.paintComponent(g)` ? – saplingPro Jun 06 '11 at 14:15
  • @Meprogrammer calling the super class's `paintComponent()` serves as clearing the canvas. – Bala R Jun 06 '11 at 14:28
  • @Meprogrammer not clearing it is what's leaving the trail so if clearing is what is required then you have to 'somehow' clear the canvas on every paint. – Bala R Jun 06 '11 at 14:36
  • 2
    @Meprogrammer sometimes the requirement is to keep drawing on the canvas without clearing what's on canvas already (in which case you don't have to call `super.paintComponent()`) . In your case, as you keep incrementing x and keep drawing more ovals, there is a trail left behind by previously drawn ovals that are still there on the canvas. So in your case, since you don't want the trail, you have to somehow clear the canvas before drawing a new oval. You can either call `super.paintComponent()` or refill the old oval with background color but usually the former is much easier to do. – Bala R Jun 06 '11 at 15:03