Hi all ,
I tried one simple animation in Swing .
Here's what the program has to do :
when a button called "play" is clicked a circle should be moved from upper left corner down to the lower right corner.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyAnimation extends JFrame {
int width;
int height;
MyAnimation animation ;
MyDrawPanel drawpanel ;
public static void main(String[] args) {
MyAnimation gui=new MyAnimation();
gui.go();
} //close main()
public void go() {
animation = new MyAnimation();
JButton button = new JButton("Play");
button.addActionListener(new ButtonListener());
drawpanel = new MyDrawPanel();
animation.setTitle("Ball Animation");
animation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
animation.getContentPane().add(BorderLayout.SOUTH,button);
animation.getContentPane().add(BorderLayout.CENTER,drawpanel);
animation.setSize(300,300);
animation.setVisible(true);
} //close go()
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.out.println("Here in action");
for(width=0,height=0;width<130&&height<130;width++,height++) {
System.out.println("before calling");
animation.repaint();
System.out.println("W ="+width+"H ="+height);
try {
Thread.sleep(50);
}catch(Exception ex) { }
} //close for
} //close actionPerformed()
} //close ButtonListener
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillRect(0,0,this.getWidth(),this.getHeight());
int w= this.getWidth();
int h = this.getHeight();
//System.out.print(w,h);
g.setColor(Color.green);
g.fillOval(width,height,40,40);
System.out.println("paintcomponent");
} //close paintcomponent()
} //closeMyDrawPanel()
} //close MyAnimation()
I noticed when a button is clicked everything goes fine(code reached Listener and loop is executed) expect that repaint() method is not invoked with in a loop.
but if I embed the same loop code with in go() method without a Listener class it's works Fine !
Why it's not happening when the code is within Litener class?
Two more additional questions :
What is the difference between calling the repaint() method with JFrame instance and JPanel instance ?
In that program in line 54 why System.out.print() method can't be invoked ?
Thanks in advance