identifying double click in java

后端 未结 4 878
小蘑菇
小蘑菇 2020-12-14 14:21

I want to know how can we perform action when mouse is double clicked in a component.

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 14:22

    The e.getClickCount()==2 is not enough if you want to allow your users to do multiple double clicks in a short delay. You are limited by the desktop configuration. You can get it by looking the result of Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");

    A good way to bypass the problem is not to use the getClickCount() check but to use a Timer where you can choose the interval max between your clicks and to handle by oneself the count (very simple).

    The code associated :

    boolean isAlreadyOneClick;
    
    @Override
    public void mouseClicked(MouseEvent mouseEvent) {
        if (isAlreadyOneClick) {
            System.out.println("double click");
            isAlreadyOneClick = false;
        } else {
            isAlreadyOneClick = true;
            Timer t = new Timer("doubleclickTimer", false);
            t.schedule(new TimerTask() {
    
                @Override
                public void run() {
                    isAlreadyOneClick = false;
                }
            }, 500);
        }
    }
    

    Tested with Win Xp OS and perfect.

提交回复
热议问题