我使用计时器每秒更改 JLabel 中的图标。 我在 GUI 构造函数中初始化并启动了计时器:
images[0] =new ImageIcon(getClass().getResource("connected.png"));
images[1] =new ImageIcon(getClass().getResource("notConnected.png"));
imageAnimator = new Timer(1000, animateImages());
imageAnimator.start();
并将计时器调用的方法包装在 swingWorker 线程中:
private ActionListener animateImages() {
System.out.println("in animateIMages method");
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
protected Void doInBackground() throws Exception {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
System.out.println("In swingworker ");
if (currentImage==0) {
currentImage=1;
connectionStatusLabel.setIcon(images[currentImage]);
System.out.println("in if currentImage==0: currentIMage should now be 1: "+ currentImage);
}
else {
currentImage=0;
connectionStatusLabel.setIcon(images[currentImage]);
System.out.println("in if else: currentIMage should now be 0: "+ currentImage);
}//end else
return null;
}
};//end worker thread
但是,图像仅在执行第一个 if 语句时更改一次。 提前致谢
最佳答案
And wrapped the method the timer calls in a swingWorker thread:
你不想这样做。对 GUI 的所有更新都应在 EDT 中完成。 SwingWorker 中的代码在单独的线程中执行,这不是您想要的。
唯一可能使用 SwingWorker 的情况是从磁盘读取图像。然后工作代码将读取图像,然后发布()结果。在您的情况下,图标看起来已经在内存中,因此不需要 SwingWorker。
只需使用 Timer 并直接在 ActionListener 中交换 Icon 即可。
关于java - 计时器对象不会为图像设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305550/