如何避免不必要的鼠标滚动事件并在延迟后执行代码

时间:2018-10-24 13:13:18

标签: java swt

请检查以下代码段

dashboard.addMouseWheelListener(new MouseWheelListener() {          
            @Override
            public void mouseScrolled(org.eclipse.swt.events.MouseEvent mouseEvent) {
                //doSomething
            }
        });

这将触发Scroll上的mouseEvent。问题是这将触发该事件超过10次单滚动。

1,如何仅在延迟1秒后获取上一个事件。试图找出使用Timer和ScheduledExecutorService的方法,但无法解决。

2,同样在1秒钟后,如果我再次滚动,它应该可以工作

1 个答案:

答案 0 :(得分:0)

我已经做了类似的事情

private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> scheduledFuture;
dashboard.addMouseWheelListener(new MouseWheelListener() {          
   @Override
   public void mouseScrolled(org.eclipse.swt.events.MouseEvent mouseEvent) {
    //for canceling previously scheduled.
    if(scheduledFuture != null)
        scheduledFuture.cancel(false);
    scheduledFuture  = executor.schedule(task, 1000, TimeUnit.MILLISECONDS);    
   }
});

dashboard.addDisposeListener(new DisposeListener() {    
  @Override
  public void widgetDisposed(DisposeEvent arg0) {
    executor.shutdownNow();                         
  }
});

 Callable task = () -> {                
    Platform.runLater(() -> {
      //do something
    });                                                         
 return null;
 };