2

I have this code here that instance a JFrame with a simple animation, where you click the button and keeps running by using thread. I made an UI with a button that instances the JFrame, the problem is, when I click the button again and it instances another JFrame, the animation of the second one doesn't work properly. Even if I instance, like, 5 JFrames, all of the buttons to start the animation works only with the first JFrame. What I want to do is instance as much as I want to and all of them work separately. Here is the code of the class with the animation:

public class duduleo extends JFrame implements ActionListener, Runnable{
JButton imagens;
int x=1;
static ImageIcon icon[] = new ImageIcon[11];
static JLabel l;
boolean anima=false;


public static void main(String args[]){
    JFrame janela = new duduleo();
    janela.show();
}

duduleo(){
    icon[0]= new ImageIcon("duken1.jpg");
    icon[1]= new ImageIcon("duken2.jpg");
    icon[2]= new ImageIcon("duken3.jpg");
    icon[3]= new ImageIcon("duken4.jpg");
    icon[4]= new ImageIcon("duken5.jpg");
    icon[5]= new ImageIcon("duken6.jpg");
    icon[6]= new ImageIcon("duken7.jpg");
    icon[7]= new ImageIcon("duken8.jpg");
    icon[8]= new ImageIcon("duken9.jpg");
    icon[9]= new ImageIcon("duken10.jpg");
    icon[10]= new ImageIcon("duken11.jpg");
    setSize(100,200);
    setLocation(200,150);
    getContentPane().setLayout(new GridLayout(2,1));
    imagens =  new JButton(icon[0]);
    l= new JLabel(icon[0]); 
    imagens.addActionListener(this);
    getContentPane().add(l);
    getContentPane().add(imagens);

}

public void run(){

    while(anima){
        for(int i=0;i<icon.length;i++){
            l.setIcon(icon[i]);
            try{
                Thread.sleep(100);
            }catch(Exception e){}

        }}}

public void actionPerformed(ActionEvent e){
    anima=!anima;
    Thread t;
    t = new Thread(this);
    t.start();
}}

Thanks for any help.

  • 1
    Don't run while/for loops on an EDT. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) and [Event Dispatch Thread](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) – asgs Oct 15 '12 at 14:01
  • No, there isn't another JFrame instantiated when you click the button the second time. – Dan D. Oct 15 '12 at 14:09

1 Answers1

2

I believe you are supposed to use Swing's invokeLater(), otherwise they get put on the event dispatch thread.

Take a look at the example here for a grasp on the idioms: http://www.java2s.com/Code/Java/Swing-JFC/Swinginvokelater.htm

Also see:

use of invokeLater

Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?

When to use SwingUtilies.invokeAndWait/invokeLater

Should i use SwingUtilities.invokeLater() inside of SwingWorker.doInBackground()?

Community
  • 1
  • 1
sampson-chen
  • 45,805
  • 12
  • 84
  • 81