在Java中,我的MouseMotionListener和MouseListener正在检测点击次数,而不是移动

时间:2015-03-09 05:19:34

标签: java swing mouse

所以我正在创建一个java游戏,这是我的鼠标点击被检测到,但mouseMoved根本没有运行。方法中有一个永不运行的print语句。我真的被卡住了,因为点击是在窗口注册的,鼠标动作不应该有任何问题。

鼠标是否依赖于其他任何东西,因为我真的不知道是什么导致了这一点。

感谢。

public class Mouse implements MouseListener, MouseMotionListener{

    private static int mouseX = -1;
    private static int mouseY = -1;
    private static int mouseB = -1;

    public static int getX(){
        return mouseX;
    }

    public static int getY(){
        return mouseY;
    }

    public static int getB(){
        return mouseB;
    }



    public void mouseMoved(MouseEvent e) {
        System.out.println("Mouse Moved");
        mouseX = e.getX();
        mouseY = e.getY();
    }

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}

    public void mousePressed(MouseEvent e) {
        mouseB = e.getButton();
        System.out.println(e.getX() + " " + e.getY());
    }

    public void mouseReleased(MouseEvent e) {
        mouseB = -1;
    }

    public void mouseDragged(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {

    }
}

这是我的游戏构造函数,它启动了所有内容。

public Game(){
        //cCursor();

        screen = new Screen(WIDTH, HEIGHT);
        mouse = new Mouse();
        keys = new Keyboard();
        //level = new RandomLevel(64, 64);
        level = Level.spawn;
        TileCoord pSpawn = new TileCoord(20,66);
        player = new Player(pSpawn.x(), pSpawn.y(), keys);
        player.init(level);

        addKeyListener(keys);
        addMouseListener(mouse);
    }

1 个答案:

答案 0 :(得分:3)

MouseMoitionListenerMouseListener的另一个听众,需要单独注册...

首先添加对addMouseMotionListener

的调用
addMouseListener(mouse);
addMouseMotionListener(mouse);

有关详细信息,请查看How to Write a Mouse Listener