Hey Guys,
When I run the following code. The animation does not seem to work right. When the button is clicked the circle moves from point a to b, but does not show the movement in between. If I remove the action listener code and button and run the for loop in the go procedure the animation is smooth.
Any suggestions on how to fix this within the context of the code I’ve written? I’m sure there are better ways to do this.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleAnimation implements ActionListener {
int x=70;
int y=70;
MyDrawPanel drawPanel;
public static void main (String [] args) {
SimpleAnimation gui = new SimpleAnimation();
gui.go ();
}
public void go () {
JFrame frame = new JFrame("Tom's Animation Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click To Start The Show !");
button.addActionListener (this);
drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent event){
for (int i=0; i<130; i++) {
x++;
y++;
drawPanel.repaint ();
try{Thread.sleep(50);
}catch (Exception ex){}
}
}
class MyDrawPanel extends JPanel{
public void paintComponent (Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.green);
g.fillOval (x,y,40,40);
}
}
}