[英]How to discard/coalesce repeated AWT events?
When a user does some action (such as click a button), I need to display the status in the JLabel. 当用户执行某些操作(例如单击按钮)时,我需要在JLabel中显示状态。 This status needs to disappear after 2 seconds.
这种状态需要在2秒后消失。 I use the following for that.
我使用以下内容。
Timer timer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setVisible(false);
}
});
However, it is possible that the user clicks the button many times and this timer is triggered multiple times. 但是,用户可能会多次单击该按钮,并且会多次触发此计时器。 This has an undesirable effect.
这具有不良影响。 When a button is clicked 3 times for instances.
单击一个按钮3次实例。
0th second: 1st click : label disppear at 2nd second 第0秒:第1次点击:标签在第2秒消失
1st second: 2nd click : label disppear at 3rd second 第1秒:第2次点击:标签在第3秒消失
2nd second: 3rd click : label disppear at 4th second 第二秒:第三次点击:标签在第四秒消失
Here, the label needs to disappear after the 4th second but will disappear after 2nd second. 这里,标签需要在第4秒后消失,但在第2秒后消失。 Therefore, I want this label to be hidden with a delay of 2s after only the last event
因此,我希望在最后一个事件之后隐藏此标签并延迟2秒
To handle this, I use an atomic counter. 为了解决这个问题,我使用原子计数器。
AtomicInteger counter = new AtomicInteger(0);
Each task is given a unique 'taskCounter' using counter.incrementAndGet() 使用counter.incrementAndGet()为每个任务提供唯一的“taskCounter”
. 。
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (counter.get() == taskCounter) {
infoLabel.setVisible(false);
}
}
});
timer.start();
The above is only executed if it is the last event that has been triggered. 仅当它是已触发的最后一个事件时才执行上述操作。 Ensuring that, my label stays visible at least 2 seconds after the last event.
确保我的标签在最后一次活动后至少2秒钟保持可见状态。
Is there a better way of dealing with this problem? 有没有更好的方法来处理这个问题?
Given two instances of java.swing.Timer
, let t1
fire at some some nominal rate that is less than two seconds. 给定两个
java.swing.Timer
实例,让t1
以某个小于2秒的标称速率触发。 Let the ActionListener
for t1
update the label
and invoke restart()
on t2
, which should have an initial delay of two seconds. 让
ActionListener
for t1
更新label
并在t2
上调用restart()
,它应该具有两秒的初始延迟。 Let the ActionListener
for t2
stop()
itself and invoke label.setVisible(false)
. 让
ActionListener
for t2
stop()
本身并调用label.setVisible(false)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.