Single-click events for the mouse are very helpful to us in many cases, but there is no mouse double-click event in Java. We can use the event source E.getclickcount () ==2 to determine the number of mouse clicks to achieve a mouse double-click event, such as: public class Mymouselistener
Extends Java.awt.event.MouseAdapter ... {
public void mouseclicked (MouseEvent e) ... {
System.out.println ("clicked");
int clicktimes = E.getclickcount ();
if (clicktimes = 2) ... {
System.out.println ("DOUBLC clicked!");
}
}
}
This does not meet our requirements, however, because the click event is triggered each time the double-click event is triggered. So we are trying to improve the above scheme without using the E.getclickcount () method provided by the system. Consider allowing the mouse click event to be delayed for 0.2 seconds when the first mouse click is performed. And in this time waiting for a second click, if there is a second click, then we perform a double-click event task, cancel the click Task, and then perform a click Task if you do not wait for the time to click again during this period.
The following is a timer delay click event to implement a mouse double-click event, click and double-click events do not affect each other! public class Mymouselistener
Extends Java.awt.event.MouseAdapter ... {
Private static Boolean flag=false;//used to determine if a double-click event has been performed
private static int clicknum=0;//to determine whether the double-click event is performed
public void mouseclicked (MouseEvent e) ... {
Final MouseEvent me=e;//Event source
this.flag=false;//each time you click the mouse to initialize the double click event flag to False
if (This.clicknum = 1) ... {//double-click event when clicknum==1
This.mousedoubleclicked (Me)//double-click event
this.clicknum=0;//initialize the double-click event execution flag to 0
this.flag=true;//Double-click Event executed, event flag is true
Return
}
Defining timers
Java.util.Timer timer=new Java.util.Timer ();
Timer starts execution, delays 0.2 seconds to determine if click event is performed
Timer.schedule (New Java.util.TimerTask () ... {
private int n=0;//record timer execution times
public void run () ... {
if (Mymouselistener.flag) ... {//If the double-click event has already been executed, then cancel the click execution directly
n=0;
mymouselistener.clicknum=0;
This.cancel ();
Return
}
if (n = = 1) ... {//Timer waits 0.2 seconds, the double-click event still does not occur, the Click event is executed
Mousesingleclicked (me);//Performing Click events
Mymouselistener.flag = true;
mymouselistener.clicknum=0;
n=0;
This.cancel ();
Return
}
clicknum++;
n++;
}
},new java.util.Date (), 500);
}
/** *//**
* Mouse Click event
* @param e Event Source parameters
*/