最近在freelancer上闲逛到别人的一个小问题,大概就是如果电脑是触摸屏的,不能正确的响应swing里的鼠标事件。
这是原代码段:
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointList = new ArrayList<>();
pointList.add(e.getPoint());
startDrag = true;
}
public void mouseReleased(MouseEvent e) {
pointList.add(e.getPoint());
lineList.add(pointList);
pointList = new ArrayList<>();
startDrag = false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
pointList.add(e.getPoint());
repaint();
}
});
表现出来的效果为在移动过程中可以看到绘画痕迹,松手时消失。
经过分析,java swing在触摸屏时表现顺序为先触发mouseDragged事件,当松手时才调用mousePressed事件和mouseReleased事件,所以不能正确保留痕迹。
以下是一种面向项目偷懒式的改法(即干脆不在pressed事件里初始化),更多对于正经的触屏的支持可以了解以下awt。
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
pointList.add(e.getPoint());
lineList.add(pointList);
pointList = new ArrayList<>();
startDrag = false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
startDrag = true;
pointList.add(e.getPoint());
repaint();
}
});