如何在mouseDragged中控制MouseEvents的频率(MouseEvent me)

时间:2013-05-09 15:34:39

标签: java events mouseevent

示例:

当我在屏幕上单击并拖动鼠标时,系统会选中并注册每个MouseEvent,直到我释放。举个例子,让我们说点击并拖动一定距离会产生10个事件。我希望系统能够接收并注册其他所有MouseEvent,这样在屏幕上拖动相同距离的鼠标只会产生5个MouseEvents。

有没有办法控制这个?那么mouseDragged(MouseEvent me)是如何工作的呢?比如,什么决定了鼠标被拖动时调用的频率,是否可以由用户控制?

1 个答案:

答案 0 :(得分:0)

在我的项目中,我这样做:

public class MyClass implements MouseMotionListener { 

    private static final long               EVENT_FREQUENCY = 200; //ms
    private ScheduledExecutorService        scheduler = Executors.newScheduledThreadPool(1);
    private ScheduledFuture<?>              mouseDraggedFrequencyTimer;
    private MouseEvent                      lastDragEvent;

    public MyClass() {
        this.addMouseMotionListener(this);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        lastDragEvent = e;
        if (mouseDraggedFrequencyTimer == null || mouseDraggedFrequencyTimer.isCancelled() || mouseDraggedFrequencyTimer.isDone()) {
            mouseDraggedFrequencyTimer = scheduler.schedule(new Runnable() {

                @Override
                public void run() {
                    System.out.println("DragEvent called: " + lastDragEvent.getX());
                }
            }, EVENT_FREQUENCY, TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {

    }
}