1

I have a simple animation programe in java swing. But it is not working.

    try{
    for(int i = 1; i<=500; i++){    
    ImageIcon icon = new ImageIcon("img\\COVERFront.jpg");
    Image image = icon.getImage();
    Image scaled =  image.getScaledInstance(400, i, 0);
    jLabel2.setIcon(new ImageIcon(scaled));
    Thread.sleep(1000);
    }
    }
    catch(InterruptedException ie){}

I am working in netbeans 7.1.

Charles
  • 50,943
  • 13
  • 104
  • 142
Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35

2 Answers2

5

From your code I understand that you are trying to animate a icon by increasing(upscaling) its size. However since the sleeping tasks is done on the event dispatch thread(EDT) it causes the GUI to freeze. So all time taking tasks such as Thread.sleep() should not be run on the Event Dispatch Thread.

Consider Using SwingUtilities or timer

Community
  • 1
  • 1
Extreme Coders
  • 3,441
  • 2
  • 39
  • 55
-1

just put the entire for loop within a thread. Something like

new Thread(){
    for(int i = 1; i<=500; i++){    
        ImageIcon icon = new ImageIcon("img\\COVERFront.jpg");
        Image image = icon.getImage();
        Image scaled =  image.getScaledInstance(400, i, 0);
        jLabel2.setIcon(new ImageIcon(scaled));
        Thread.sleep(1000);
    }
}

this would do. You tried to animate the same in Event Dispatcher Thread is the only problem.

Akhil K Nambiar
  • 3,835
  • 13
  • 47
  • 85
  • 3
    This might work, sometimes... violating the Swing threading rules by accessing Swing components on another thread is not a good idea. – Robin Nov 21 '12 at 07:23
  • @Robin so how do I take this forward? – Akhil K Nambiar Nov 21 '12 at 07:29
  • 1
    Look at the answer of @Algortihms. You need to sleep on a separate thread and perform the swingoperations on the EDT. This can either be done by using the `SwingUtilities` class or by using the `javax.swing.Timer` (where you set the delay instead of using `Thread.sleep`) – Robin Nov 21 '12 at 07:40