java接口防抖_java swing 防抖机制

从问题开始说.

我们产品的 操作台(workbench) 是一个java swing程序. 有一个event handler的代码如下:

public voidactionPerformed(ActionEvent e) {//做耗时的工作, 如插入数据库

}

现在的一个问题在于, 如果用户连续点了两次button, 则event handler被执行两次, 则用户会得到 主键重复错误.

简单的想法是 在event handler的开头结尾把 对应的ok button给disable/enable.

public voidactionPerformed(ActionEvent e) {try{//disable OK 按钮...//做耗时的工作

} finally{//enable OK 按钮...

}

}

但上面这段代码是错误的.

event dispatch thread的工作流程:

enter handling code of event1 -> disable button -> enable button -> enter handling code of event2

正确的实现:

public voidactionPerformed(ActionEvent e) {try{//disable OK 按钮...//做耗时的工作

} finally{

SwingUtilities.invokeLater(newRunnable(){

@Overridepublic voidrun() {//enable OK 按钮...

}});

}

}

event dispatch thread的工作流程:

enter handling code of event1 -> disable button -> ignore event2 -> enable button

If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed.

references:

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/

https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值