关于:
timeDelay(2); // A method that delays 2 secs - it works
不,它不起作用,无论你如何测试它。 Swing不会那样工作,你最好避免做出这样的假设。使用Swing Timer。
您会问,我怎么知道它不起作用,我会告诉您:该代码不会调用后台线程,也不会启动Swing Timer,所以它唯一能做的就是延迟当前线程,可能是Thread.sleep(...)的某个地方。如果你调用它并“测试”这个,是的,它会导致System.out.println(...)语句中出现的延迟出现在控制台上,但它也会睡眠Swing事件线程,并让你的应用程序进入休眠状态。所以你真的不想这样做。
事实上,在Swing中查看是否有效的最佳测试是您当前的代码。那么会发生什么?你说:
When I push the button, it waits some time, and from the 1st goes to the last image, and skips the images from the folder one-by-one
所以实际上你知道你的延迟对Swing没有用,因为你描述了在Swing事件线程上踩踏的代码的经典症状,让它瘫痪。所以再次使用Swing Timer。这是一个link to the Swing Timer Tutorial。
如果这是我的代码,那么每次按下按钮时我都不会读取图像,而是一次性读取它们,而只读取一次并将它们放在ArrayList中,称为iconList。假设您这样做,那么代码可能如下所示:
private void buttonShowImageActionPerformed(java.awt.event.ActionEvent evt) {
// !! I'd use a variable or constant instead of the magic number 2000
new Timer(2000, new ActionListener() {
int count = 0;
actionPerformed(ActionEvent e) {
if (count != iconList.size()) {
labelImage.setIcon(iconList.get(count));
count++;
} else {
// stop the Timer
((Timer) e.getSource()).stop();
}
}
}).start();
}
编辑结果
你问:
My friend one last question ..... I put the "int count = 0;" inside the actionPerformed and nothing happend ... I cannot understand why it works only if it is outside the method .... ?
请理解Swing Timer的工作方式是重复调用actionPerformed方法,这里每2000秒一次。我的代码所做的是,当计时器启动时,计数设置为0.每次调用actionPerformed方法时,计数增加1,并显示下一个ImageIcon。
使用您的代码,当调用actionPerformed方法时,将计数重新设置为0,显示第一个图像,然后递增计数。但每次调用actionPerformed方法时,您的代码会将计数重置为0,因此增量无效。