[英]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
并通过mousepressed
和mousepressed
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, 你应该考虑
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.