Thread.sleep(1000) not working in Swing

2019-02-28 17:32发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-02-28 18:06

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

查看更多
ら.Afraid
3楼-- · 2019-02-28 18:10

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.

查看更多
登录 后发表回答