在Java中,如何在按下鼠标按钮时侦听鼠标移动事件

在Java中,如何在按下鼠标按钮时侦听鼠标移动事件,java,mouseevent,mouse,mousemove,Java,Mouseevent,Mouse,Mousemove,我的程序中的鼠标事件有问题。我正试图用画布编写一个绘图程序 如果用户左键单击并移动鼠标,则应进行绘制。因此,我定义了一个类Drawer,其中包含一个boolean allow\u draw,并添加了一个方法draw 使用画布中的mousemoved事件调用draw,并使用mousepressed和released将allow\u draw设置为true和false 但是,当我按下鼠标按钮时,mousemoved没有启动 我的问题是:当按下鼠标按钮时,我如何能听到鼠标的移动 希望你知道我在找什么:

我的程序中的鼠标事件有问题。我正试图用画布编写一个绘图程序

如果用户左键单击并移动鼠标,则应进行绘制。因此,我定义了一个类
Drawer
,其中包含一个
boolean allow\u draw
,并添加了一个方法
draw

使用画布中的
mousemoved
事件调用
draw
,并使用
mousepressed
released
allow\u draw
设置为true和false

但是,当我按下鼠标按钮时,
mousemoved
没有启动

我的问题是:当按下鼠标按钮时,我如何能听到鼠标的移动


希望你知道我在找什么:)

你能发布你的源代码吗?请尝试添加MouseMotionListener。下面是我正在从事的一个项目的一个例子

addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {

        public void mouseDragged(java.awt.event.MouseEvent evt) {
            formMouseDragged(evt);
        }
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            formMouseMoved(evt);
        }
    });`

你能发布你的源代码吗?请尝试添加MouseMotionListener。下面是我正在从事的一个项目的一个例子

addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {

        public void mouseDragged(java.awt.event.MouseEvent evt) {
            formMouseDragged(evt);
        }
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            formMouseMoved(evt);
        }
    });`

按下按钮的鼠标移动事件将是拖动事件。只要听一听“MouseListener#mouseDragged”,这就是你要找的

按下按钮的鼠标移动事件将是拖动事件。只要听一听“MouseListener#mouseDragged”,这就是你要找的
  • 使用MouseListener和MouseMotionListener的组合,这在MouseAdapter类中很方便地组合
  • 当鼠标按下时打开绘图
  • 发生鼠标滑动时关闭绘图
  • 如果绘图处于打开状态,则在鼠标标记内绘图(使用if块)
  • 使用
    addMouseListener(…)
    方法和
    addMouseMotionListener(…)
    方法将MouseApter对象添加到组件中两次

你应该考虑,

  • 使用MouseListener和MouseMotionListener的组合,这在MouseAdapter类中很方便地组合
  • 当鼠标按下时打开绘图
  • 发生鼠标滑动时关闭绘图
  • 如果绘图处于打开状态,则在鼠标标记内绘图(使用if块)
  • 使用
    addMouseListener(…)
    方法和
    addMouseMotionListener(…)
    方法将MouseApter对象添加到组件中两次

我不清楚为什么需要“允许绘制”标志,但请注意,请确保正确同步访问以允许绘制。否则,该变量的货币将出现问题。谢谢,现在它可以工作了!:)我在主类和设计器类的构造函数中编写了'public CanvasTest(){initComponents();this.drw=new Drawer(this);this.canvas.addMouseMotionListener(new MouseMotionListener(this));this.canvas.addMouseMotionListener(new mouseclickllistener(this));//this.canvas.addMouseMotionListener(新的MouseMotion(this));}`对不起,代码高亮显示对我不起作用……但我像你一样:)我不清楚你为什么需要'allow_draw'标志,但请注意,请确保正确同步访问以允许_draw。否则,该变量的货币将出现问题。谢谢,现在它可以工作了!:)我在主类和设计器类的构造函数中编写了'public CanvasTest(){initComponents();this.drw=new Drawer(this);this.canvas.addMouseMotionListener(new MouseMotionListener(this));this.canvas.addMouseMotionListener(new mouseclickllistener(this));//this.canvas.addMouseMotionListener(新的MouseMotion(this));}`对不起,代码高亮显示对我不起作用……但我还是像你一样:)