import com.other.TimerUtils;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* 单机 双击 长按
*/
public abstract class MyMouseListener extends MouseAdapter {
private static boolean flag = false;//用来判断是否已经执行双击事件
private static int clickNum = 0;//用来判断是否该执行双击事件
private Timer newTimer;
private boolean isExeLong;
/**
* 鼠标按下事件发生时调用的方法。当用户按下鼠标按钮时触发,可以通过MouseEvent对象获取有关鼠标按下的信息。
*/
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
// 鼠标左键按下
if (newTimer != null) {
return;
}
isExeLong = false;
newTimer = TimerUtils.startTimer(new Runnable() {
@Override
public void run() {
System.out.println("long");
stopTimer();
onLongClick(e);
isExeLong = true;
stopTimer();
// isExeLong = false;
}
}, 1000);
}
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
stopTimer();
}
@Override
public void mouseClicked(MouseEvent e) {
final MouseEvent me = e;//事件源
this.flag = false;//每次点击鼠标初始化双击事件执行标志为false
if (this.clickNum == 1) {//当clickNum==1时执行双击事件
if (isExeLong) return;
stopTimer();
this.mouseDoubleClicked(me);//执行双击事件
this.clickNum = 0;//初始化双击事件执行标志为0
this.flag = true;//双击事件已执行,事件标志为true
return;
}
//定义定时器
Timer timer = new Timer();
//定时器开始执行,延时0.2秒后确定是否执行单击事件
timer.schedule(new TimerTask() {
private int n = 0;//记录定时器执行次数
public void run() {
if (MyMouseListener.flag) {//如果双击事件已经执行,那么直接取消单击执行
n = 0;
MyMouseListener.clickNum = 0;
this.cancel();
return;
}
if (n == 1) {//定时器等待0.2秒后,双击事件仍未发生,执行单击事件
if (!isExeLong) {
stopTimer();
mouseSingleClicked(me);//执行单击事件
}
MyMouseListener.flag = true;
MyMouseListener.clickNum = 0;
n = 0;
this.cancel();
return;
}
System.out.println("n = " + clickNum);
clickNum++;
n++;
}
}, new Date(), 200);
}
/**
* 鼠标单击事件
*
* @param e 事件源参数
*/
public abstract void mouseSingleClicked(MouseEvent e);
/**
* 鼠标双击事件
*
* @param e 事件源参数
*/
public void mouseDoubleClicked(MouseEvent e) {
// System.out.println("Doublc Clicked!");
}
/**
* 鼠标长按事件
*
* @param e 事件源参数
*/
public void onLongClick(MouseEvent e) {
// System.out.println("onLongClick Clicked!");
}
private void stopTimer() {
if (newTimer == null) {
return;
}
newTimer.cancel();
newTimer = null;
}
}
标签:单机,MouseEvent,void,双击,clickNum,事件,swing,public
From: https://blog.51cto.com/u_11288266/8005179