如何在Java中按下鼠标按钮时收听鼠标移动事件
问题描述:
我在程序中遇到了鼠标事件问题。我试图用画布编写一个绘图程序。如何在Java中按下鼠标按钮时收听鼠标移动事件
如果用户左键单击并移动鼠标,应绘制图形。所以我在其中定义了Drawer
类,其中boolean allow_draw
,并且我添加了一个方法draw
。
draw
被称为在画布mousemoved
事件和allow_draw
设置真假与mousepressed
和released
。
然而,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);
}
});`
答
鼠标移动事件与按下按钮将是一个拖动事件。只需听'MouseListener#mouseDragged',这就是你要找的。使用的MouseListener和MouseMotionListener和,这是在MouseAdapter类方便地组合的组合
答
你应该考虑,
- 。
- 当mousePressed发生时,在上转动绘图。
- 打开绘图关闭时如果的mouseReleased图是上(使用IF块)发生内的mouseDragged
- 绘图。
- 使用
addMouseListener(...)
方法和addMouseMotionListener(...)
方法将您的MouseAdapter对象两次添加到组件。
我不清楚为什么您需要'allow_draw'标志,但请注意,请确保您正确同步allow_draw。否则,您将遇到该变量货币的问题。 – RWVan3
谢谢,现在它工作! :) 我写在我的主要和设计器类的构造函数 ' public CanvasTest(){ initComponents(); this.drw =新的抽屉(this); this.canvas.addMouseMotionListener(new MouseMotionListener(this)); this.canvas.addMouseListener(new MouseClickListener(this)); //this.canvas.addMouseMotionListener(new MouseMotion(this)); } ' – user1795687
抱歉,codehighlighting不会对我工作...但我做你:) – user1795687