问题描述
由于我不是CS专业,我在将编程愿望转化为实际课程时遇到了一些困难。
它基本上归结为以下内容:如何在标签上交替显示图像,每张图像显示特定于每个图像的时间量。
现在,我可以很容易地将图像加载到面板上,而且我已经管理好了使用KeyListener和东西捕获用户输入,这些都非常好用,并且比我预期的要容易得多。我也知道如何使用循环结构,如while,for和do..while,但这个计时器业务是阴暗的。
我看到各种使用线程的东西,什么不是,我真的不需要它。这不是关于有效的编程或良好的代码,它只是关于展示某些东西。
任何帮助将不胜感激!
使用。 SwingWorker的doInBackground方法应该如下所示:
@Override
protected Void doInBackground(){
尝试{
while(true){
displayImage(imageA);
Thread.sleep(1000L);
if(isCancelled()){
return null;
}
displayImage(imageB);
Thread.sleep(200L);
if(isCancelled()){
return null;
}
}
}
catch(InterruptedException e){
// ignore
}
返回null;
}
private void displayImage(final Icon image){
SwingUtilituies.invokeLater(new Runnable(){
@Override
public void run() {
//在面板中显示图像
}
});
}
keylistener应该只是取消SwingWorker。
Since I'm not a CS major, I'm having some difficulties translating my programming wishes into an actual program.What it basically boils down to is the following: how can I alternate an image on a label, showing each image for an amount of tim specific for each image.
So: say I've images A and B; I'd like the user to see A for 1000ms and B for 200ms. This keeps on looping until a user presses a certain key.
Now, I'm able to load an image onto a panel, quite easily even, and I've managed to catch user input using KeyListener and stuff, which all works quite nicely and alot easier then I had expected. I also know how to use looping constructs like while, for and do..while, but this timer business is shady.
I see all kinds of stuff using threads and what not, I really don't need that. This is not about efficient programming or good code, it's simply about demonstrating something.Any help would be greatly appreciated!
Use a SwingWorker<Void, Void>
. The doInBackground method of the SwingWorker should look like this :
@Override
protected Void doInBackground() {
try {
while (true) {
displayImage(imageA);
Thread.sleep(1000L);
if (isCancelled()) {
return null;
}
displayImage(imageB);
Thread.sleep(200L);
if (isCancelled()) {
return null;
}
}
}
catch (InterruptedException e) {
// ignore
}
return null;
}
private void displayImage(final Icon image) {
SwingUtilituies.invokeLater(new Runnable() {
@Override
public void run() {
// display the image in the panel
}
});
}
The keylistener should simply cancel the SwingWorker.
这篇关于使用java使用计时器交替显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!