我想知道如何阻止mousedMoved被解雇。我一直在谷歌搜索,但找不到答案。有这个方法吗?我正在使用eclipse并经历了mouseevent方法但却找不到任何东西。
public class Drawing extends JPanel {
private ArrayList<Point> pointList;
private int counter = 0;
public Drawing() {
setLayout(new FlowLayout());
setBackground(Color.white);
pointList = new ArrayList<Point>();
addMouseListener(new MouseTrackerListener());
}
public void paintComponent(Graphics pen) {
super.paintComponent(pen);
for (int i = 0; i < pointList.size(); i++) {
Point p = pointList.get(i);
pen.fillOval(p.x, p.y, 10, 10);
}
}
private class MouseTrackerListener extends MouseInputAdapter {
public void mouseClicked(MouseEvent e) {
counter++;
if (counter % 2 != 0) {
addMouseMotionListener(new MouseTrackerListener());
} else {
System.out.println("Hi");
}
}
public void mouseMoved(MouseEvent e) {
Point point = e.getPoint();
pointList.add(point);
repaint();
}
}
答案 0 :(得分:1)
如果图纸处于绘图状态,您可以创建boolean
来切换。您将boolean
命名为isDrawingMode
所以当你点击鼠标时...你把它设置为假,如果你再次点击它,它将成为真;
您需要做的就是在点击鼠标时切换boolean isDrawingMode
所以你的mousemoved listener
看起来像这样
public void mouseMoved(MouseEvent e) {
if (!isDrawingMode) return; //if isDrawingMode is false, it will not trigger to draw
Point point = e.getPoint();
pointList.add(point);
repaint();
}
答案 1 :(得分:0)
For Java
您可以为侦听器使用公共基类,并在其中使用静态方法打开或关闭侦听器:
public abstract class BaseMouseListener implements ActionListener{
private static boolean active = true;
public static void setActive(boolean active){
BaseMouseListener.active = active;
}
protected abstract void doPerformAction(ActionEvent e);
@Override
public final void actionPerformed(ActionEvent e){
if(active){
doPerformAction(e);
}
}
}
您的听众必须实现doPerformAction()而不是actionPerformed()。
我不知道您使用哪种语言或您的代码是什么。 在Jquery中,我通常使用以下2种方法代码
M1:取消绑定另一个事件。
OR M2:您应该在此事件调用结束时添加event.stopPropagation()以停止传播..
M1代码示例:
else if(e.type == 'click')
{
$(window).unbind('mousemove')
}
But really you should name the event so you only unbind the appropriate event listener.
Bind : $(window).bind('mousemove.dragging', function(){});
Unbind : $(window).unbind('mousemove.dragging', function(){});
M2代码示例:
$("#rightSubMenu").mousemove(function(e){
// You code...
e.stopPropagation();
});
额外信息
有关详细信息,请参阅以下标记 Disable mousemove on click How to stop mousemove() from executing when the element under the mouse moves?