java让两张图交替出现在窗口上,使用java使用计时器交替显示图像

Java实现两张图在窗口交替显示
博主非计算机专业,编程遇困难,想实现两张图在窗口交替显示,如A图显示1000ms,B图显示200ms,循环至用户按键。博主能加载图片、捕获用户输入,但对定时器操作不熟悉。解决方案是使用SwingWorker,按键监听器取消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. 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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值