Java : ignore single click on double click?

两盒软妹~` 提交于 2019-11-30 04:54:23

Indeed you'll need to set up a Timer in your overridden mouseClicked() method of your MouseAdapter to detect the time interval between the two clicks. The default interval in ms can be found by querying Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"). If another mouse click is detected before the timer expires, then you have a double-click, else once the timer expires, you can process the single-click.

Actually I think there is a simpler solution (use InputEvent's getWhen() method):

class DCListener extends MouseAdapter{

    private long maxTimeBetweenClicks; // in millis
    private long firstClickTime=0;
    private Runnable eventHandler;

    public DCListener(long maxTimeBetweenClicks,Runnable eventHandler){
        this.maxTimeBetweenClicks=maxTimeBetweenClicks;
        this.eventHandler=eventHandler;
    }

    public void mouseClicked(MouseEvent e){

        if((e.getWhen()-firstClickTime)<=maxTimeBetweenClicks){
            firstClickTime=0; // 3 clicks are not 2 double clicks
            eventHandler.run();
        }else{
            firstClickTime=e.getWhen();
        }

    }
}

Have you tried implementing the MouseListener interface already?

I think MouseEvent has a click count method ( or property ) to know that.

I bet you have gone through that already, so what is the problem you're facing there?

Probably what you can do is to code the time interval elapsed between a single and a double click with a thread or something.

So a single click will only be valid if another click is not issued in let's say 300 ms. ( something configurable )

The idea is:

public void listen for the single click() 
    if (  in x time there has not been another click  ) 
    then 
        we have a single click
        proceed with your single click handling
    else 
        we have a double click
       proceed with your double click handling

Or something like that.

An alternative solution:

I figured out this before I found the solution in this question. The idea is the same, use a timer, although more complicated :).

Use SwingWorker:

class BackgroundClickHandler extends SwingWorker<Integer, Integer> {
  @Override
  protected Integer doInBackground() throws Exception {
    Thread.sleep(200);
    // Do what you want with single click
    return 0;
  }

}

In mouseClicked() method you can do something like this:

 if (event.getClickCount() == 1) {
  // We create a new instance everytime since
  // the execute() method is designed to be executed once
  clickHandler = new BackgroundClickHandler();

  try {
    clickHandler.execute();
  } catch(Exception e) {
    writer.println("Here!");
  }
}

if (event.getClickCount() == 2) {
  clickHandler.cancel(true);

  //Do what you want with double click
}

I hope it be useful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!