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();
   } //close main()
   public void go() {
       animation = new MyAnimation();
       JButton button = new JButton("Play"); 
       button.addActionListener(new ButtonListener());
       drawpanel = new MyDrawPanel();      
       animation.setTitle("Ball Animation");
   } //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");
                   System.out.println("W ="+width+"H ="+height);
               try {
               }catch(Exception ex) { }
         }  //close for
     }  //close actionPerformed()
 }  //close ButtonListener
      class MyDrawPanel extends JPanel {
            public void paintComponent(Graphics g) {
               int w= this.getWidth();
               int h = this.getHeight();
           } //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

im not 100% sure on this but i think when you extend jframe, the method used to init the window is called initComponents. So when you override that it is called automatically. On line 54 it is the same thing, paintcomponents inits the window and all the variables are final so you cant manipulate them. once again im not 100% on that, anyone else got ideas?

This article has been dead for over six months. Start a new discussion instead.