停止鼠标移动

5f0d552i  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(331)

我想知道如何阻止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();

    }
}
wqsoz72f

wqsoz72f1#

对于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()。
更多信息:如何临时禁用swing中的事件侦听器?
我不知道你用哪种语言,也不知道你的代码是什么。在jquery中,我通常使用以下两种方法代码
m1:解除一个事件与另一个事件的绑定。
或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();
});

额外信息
有关更多信息,请参见以下标记禁用鼠标移动单击如何在鼠标下的元素移动时停止执行mousemove()?

9vw9lbht

9vw9lbht2#

您可以创建 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();

}

相关问题