简体   繁体   English

Thread.sleep(1000)无法在Swing中工作

[英]Thread.sleep(1000) not working in Swing

I have a simple animation programe in java swing. 我在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. 我在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. 但是,由于睡眠任务是在事件调度线程(EDT)上完成的,因此会导致GUI冻结。 So all time taking tasks such as Thread.sleep() should not be run on the Event Dispatch Thread. 因此,不应该在Event Dispatch Thread上运行Thread.sleep()等任务。

Consider Using SwingUtilities or timer 考虑使用SwingUtilities计时器

just put the entire for loop within a thread. 只需将整个for循环放在一个线程中。 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. 你试图在Event Dispatcher中设置相同的动画线程是唯一的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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