Search code examples
javaswingmouseeventactionlistenermouselistener

How to count clicks with mouselistener and timer


So I am having a bit of trouble writing a mouse listener because I want the action to be performed only on a double click. I am trying to use a timer to reset a value that keeps track of the clicks but I don't think I have the correct understanding of the timers.

 getTable().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e)
      {
          if ( isClickedOnce && SwingUtilities.isLeftMouseButton(e))
          {
              isClickedOnce = false;
              System.out.println("anything");
          }
          else if(SwingUtilities.isLeftMouseButton(e))
          {
              isClickedOnce = true;
              Timer time = new Timer(1000,new ActionListener(){
              public void actionPerformed(ActionEvent actionEvent)
                            {isClickedOnce=false;}
              });
              time.start();
              }
          }
      });

Solution

  • Java will do this for you. Within mouseClicked():

    if(e.getClickCount() == 2) {
      // do something
    }