简体   繁体   中英

Thread.sleep(1000) not working in Swing

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM