Dear all i am trying to write a java program to move ball in Applet. i have written the code as following, its moving the ball but the behaviors is not as i want . There should only be one ball appearing. Thanks in advance.
Calling super.paint(g); as the first line in the paint method should take care of that.
But you're making an often made mistake by sleeping on the Event Dispatcher Thread. Read Concurrency in Swing for more information. In this case, a javax.swing.Timer should be a better option.
Rob Spoor, thanks for your help . I inserted super.paint(g) as first statement in for loop, it is making the old image disapear but only afetr for loop executes four times , i want to see only one image at one time , further help would be appreciated and thanks for suggesting javax.swing.Timer, i would try it.
Joined: Oct 17, 2008
ok, i made few changes in the logic to erase the previous image plus some additional functionality to revert the ball back to its original position and it worked thanks for helping guys.
Dear Rob Spoor will you please help me how can i do this by using javax.swing.Timer instead of sleep() methd. thanks
Step 1: get rid of Thread.sleep and the current call to repain(). Causing a repaint from a painting method will cause an infinite painting loop that will cause your CPU usage to go up.
Step 2: get rid of the Thread variable completely.
Step 3: create a javax.swing.Timer object. Create a new ActionListener (an anonymous inner class will be good); this ActionListener will call the repaint method in its actionPerformed method.
Step 4: tweak the timer's settings as necessary.
Step 5: start the timer.
Step 6: enjoy your program.
You got the right idea how you want your program to execute but you are delegating the responsibility incorrectly. The paint method should only paint, one frame at a time, it is not responsible for the flow of the program. Another function or inner class should be responsible for the timing operations and call the paint() method.