java取消按钮,Java swing:选择/取消选择JButton来模仿脉冲

本文讨论了如何在Java Swing应用中避免在非UI线程中操作GUI对象,建议使用Swing Timer来实现邮件客户端中按钮的吸引注意力效果。通过定时器改变按钮的选中状态,创建了一种闪烁效果,同时提供了停止闪烁的逻辑。博客还包含了Swing Timer的使用示例代码。
摘要由CSDN通过智能技术生成

f.e. I have an email client, it receives new message, button with incoming messages starts doing something, until user clicks it to see whats up.

I'm trying to make button attract attention by selecting, waiting and then deselecting it, but this does nothing!

do{

button.setSelected(true);

Thread oThread = new Thread() {

@Override

public void run() {

synchronized (this) {

try {

wait(1000);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

button.setSelected(false);

}

};

oThread.start();

}while(true);

解决方案

You should use Swing timers for that. Don't interact with GUI objects from foreign threads.

There's some docs in the Java tutorial: How to use Swing timers.

Here's an example way you could do this playing with the button's icon.

// member var

Icon buttonIcon;

Timer timer;

// in constructor for example

buttonIcon = new ImageIcon("resources/icon.png");

button.setIcon(buttonIcon);

timer = new Timer(1000, this);

timer.start();

// in the actionPerformed handler

if (button.getIcon() == null)

button.setIcon(icon);

else

button.setIcon(null);

Your class will need to implement ActionListener for this to work like that. Add some logic to stop the flashing when you need it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值