简体   繁体   English

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

[英]How to listen to mouse move-events while mouse button is pressed in Java

I have a problem with mouse events in my program. 我的程序中的鼠标事件有问题。 I'm trying to code a drawing program with a canvas. 我正在尝试使用画布编写绘图程序。

The user should draw if he left-clicks and moves the mouse. 如果用户左键单击并移动鼠标,则应进行绘制。 So I defined a class Drawer with a boolean allow_draw in it, and I added a method draw . 因此,我定义了一个带有boolean allow_draw的类Drawer ,并添加了一个draw方法。

draw is called with a mousemoved event in the canvas and allow_draw is set true and false with mousepressed and released . 在画布中通过mousemoved事件调用draw并通过mousepressedmousepressed released allow_draw设置为true和false。

However, mousemoved isn't firing while I press the mouse button... 但是,当我按下鼠标按钮时, mousemoved无法启动...

My question is: how can I listen to mouse movements while a mouse button is pressed. 我的问题是:如何在按下鼠标按钮时听取鼠标的移动。

Hope you know what I'm looking for :) 希望你知道我在找什么:)

Can you please post your source code? 您能发布您的源代码吗? Please try adding a MouseMotionListener. 请尝试添加MouseMotionListener。 Here is an example from a project I am working on. 这是我正在从事的项目的示例。

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);
        }
    });`

You should consider, 你应该考虑

  • using a combination of MouseListener and MouseMotionListener, which is conveniently combined in the MouseAdapter class. 使用MouseListener和MouseMotionListener的组合,可以方便地在MouseAdapter类中进行组合。
  • Turn drawing on when mousePressed occurs. 打开时发生的mousePressed 绘图。
  • Turn drawing off when mouseReleased occurs 当发生mouseReleased时关闭绘图
  • Draw within mouseDragged if drawing is on (use an if block). 如果在绘图上打开,则在mouseDragged中绘制(使用if块)。
  • Add your MouseAdapter object twice to the component, with the addMouseListener(...) method and the addMouseMotionListener(...) method. 使用addMouseListener(...)方法和addMouseMotionListener(...)方法将MouseAdapter对象两次添加到组件。

A mouse move event with a pressed button would be a drag event. 按下按钮的鼠标移动事件将是拖动事件。 Simply listen to 'MouseListener#mouseDragged', it is what you're looking for. 只需听“ MouseListener#mouseDragged”,这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM