1

我一直在开发一个基本的塔防游戏,并希望跟踪鼠标的移动。我不需要它在拖动时跟踪鼠标移动,而只是在将鼠标悬停在屏幕上时,以便用户可以看到要放置塔的位置。我已经扩展了 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);
    }
}

任何帮助表示赞赏。谢谢!

4

2 回答 2

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);
    }
}
于 2013-08-19T19:51:50.883 回答
1

如何将 MouseController 添加到代码中?我认为 MouseAdaptor 实现了 MouseListener 和 MouseMotionListener。确保也打电话component.addMouseMotionListener(myMouseController),而不仅仅是component.addMouseListener(myMouseController)。If only mouseClickedis called but not mouseMoved,听起来您只是将鼠标控制器添加为鼠标侦听器,但尚未添加为鼠标运动侦听器。

于 2013-08-19T21:03:50.543 回答