我一直致力于基本的塔防游戏,并且正在寻找跟踪鼠标的动作。拖动时我不需要它来跟踪鼠标移动,但只是当悬停在屏幕上时,用户可以看到塔的放置位置。我已经扩展了MouseAdapter以制作一个控制器并点击放置一个塔,但我无法想象如何跟踪鼠标移动。应该覆盖mouseMoved吗?我尝试了一点点成功。在发表一个印刷声明之后我可以看到该事件没有被解雇。这就是我目前所拥有的:
public class MouseController extends MouseAdapter {
private final Board my_board;
private final int square_size;
public MouseController(final Board the_board, final int the_square_size) {
my_board = the_board;
square_size = square_size;
}
@Override
public void mouseClicked(final MouseEvent e) {
super.mouseClicked(e);
Point p = e.getPoint();
my_board.placeTower(p.x / square_size, p.y / square_size - 1);
}
@Override
public void mouseMoved(final MouseEvent e) {
super.mouseMoved(e);
Point p = e.getPoint();
my_board.placeCursor(p.x / square_size, p.y / square_size - 1);
}
}
感谢任何帮助。谢谢!
答案 0 :(得分:2)
这是一个官方教程,可以完全按照您的要求进行操作:http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html
以下是内联的相关摘录:
public class MouseMotionEventDemo extends JPanel
implements MouseMotionListener {
//...in initialization code:
//Register for mouse events on blankArea and panel.
blankArea.addMouseMotionListener(this);
addMouseMotionListener(this);
...
}
public void mouseMoved(MouseEvent e) {
saySomething("Mouse moved", e);
}
public void mouseDragged(MouseEvent e) {
saySomething("Mouse dragged", e);
}
void saySomething(String eventDescription, MouseEvent e) {
textArea.append(eventDescription
+ " (" + e.getX() + "," + e.getY() + ")"
+ " detected on "
+ e.getComponent().getClass().getName()
+ newline);
}
}
答案 1 :(得分:1)
如何将MouseController添加到代码中?我认为MouseAdaptor实现了MouseListener和MouseMotionListener。请务必同时致电component.addMouseMotionListener(myMouseController)
,而不仅仅是component.addMouseListener(myMouseController)
。
如果仅调用mouseClicked
但不调用mouseMoved
,则听起来您只是将鼠标控制器添加为鼠标侦听器,但还不是鼠标移动侦听器。