停止 mouseMoved

Stopping mouseMoved

我想知道如何阻止 mousedMoved 被解雇。我一直在谷歌搜索,但找不到答案。有办法吗?我正在使用 eclipse 并查看了 mousevent 方法,但就是找不到任何东西。

    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();

    }
}

For Java

您可以为您的侦听器使用一个公共基础 class,并在其中使用静态方法来打开或关闭侦听器:

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()。

More info : How to temporarily disable event listeners in Swing?

我不知道你使用的是哪种语言,也不知道你的代码是什么。 在Jquery中我一般使用以下2种方法代码

M1:解绑一个事件。

或 M2:您应该在此事件调用结束时添加 event.stopPropagation() 以停止传播..

M1 code sample:

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 Code sample:

$("#rightSubMenu").mousemove(function(e){
  // You code...
  e.stopPropagation();
});

Extra Info

有关更多信息,请参阅以下标签 Disable mousemove on click How to stop mousemove() from executing when the element under the mouse moves?

您可以创建一个 boolean 来切换是否处于绘图状态。你将 boolean 命名为 isDrawingMode

所以当你点击鼠标..你把它设置为false,如果你再点击它就会变成true;

您所要做的就是在单击鼠标时切换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();

}