I am trying to do a simple animation, in which a green circle moves diagonally in a smeared pattern on a widget named panel which is an instance of a class MyPanel which extends JPanel. The JFrame has a start button, which when pressed is supposed to start the animation by calling the actionPerformed method (in which i call the animate method which calls the repaint method while successively incrementing the x and y coordinates of the circle) in the main class which itself is the listener. But instead, when the button is pressed, the circle shows up at the initial coordinates, and then after a delay, another circle shows up at the final coordinates. Could someone please help me figure out where I am going wrong? I am a beginner in Java, who has done some basic programming in C years ago. Thanks in advance. Here is my code:
Welcome to the Ranch!
I've modified your post to UseCodeTags, and I've also added some indentation. It would be great if you could do that yourself from now on.
As I was adding the indentation I got a good look at your code. I see three problems:
3) You override paintComponent, but you a) make it public where protected will do, and b) you're not calling super.paintComponent(g); as the first statement.
2) You're catching an exception on line 45 without doing anything. This isn't a good habit because you will never notice if anything goes wrong; the least you should do is print the stack trace.
1) The most important one of all: you're sleeping on the Event Dispatcher Thread. I suggest you first read Concurrency in Swing, and then switch to using a javax.swing.Timer to do the work in your animate() method.
Thanks a ton Rob!!!
I haven't gone through threads or event handling yet, as I have just begun. Though I learnt some of Swing, and tried to make that program. I commented out that thread sleep, and it looks like this now:
But still, I don't get a smear, rather one circle at the initial coordinates, while the other(which now appears almost instantly as the thread doesn't sleep now) shows up after it at the final coordinates.