开发者

identifying double click in java

I want to know ho开发者_JAVA百科w can we perform action when mouse is double clicked in a component.


public void mouseClicked(MouseEvent event)
{
  if (event.getClickCount() == 2 && event.getButton() == MouseEvent.BUTTON1) {
    System.out.println("double clicked");
  }
}


Assuming you mean in Swing, assign a MouseListener to your Component:

addMouseListener(new MouseAdapter(){
    @Override
    public void mouseClicked(MouseEvent e){
        if(e.getClickCount()==2){
            // your code here
        }
    }
});

Reference:

  • Java Tutorial: How to write a Mouse Listener


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.


My problem is that I have to respond one way if the user single clicks, another if they click more than one time (my Swing VM seems to be able to count up to four clicks when I click multiple times). When I ran the example above, it seemed to count a triple click as a single one. So, here is my rewrite. Basically, I just have a scheduled task that waits until the dust clears and then checks the number of clicks registered. The 400 ms wait seems to work best for me.

JButton jButton = new JButton("Click Me!");
jButton.addMouseListener(new MouseAdapter() {
    private int eventCnt = 0;
    java.util.Timer timer = new java.util.Timer("doubleClickTimer", false);

    @Override
    public void mouseClicked(final MouseEvent e) {
        eventCnt = e.getClickCount();
        if ( e.getClickCount() == 1 ) {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if ( eventCnt == 1 ) {
                        System.err.println( "You did a single click.");
                    } else if ( eventCnt > 1 ) {
                        System.err.println("you clicked " + eventCnt + " times.");
                    }
                    eventCnt = 0;
                }
            }, 400);
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜