1

How do I know if the mouse if out of the window I made and from which side it exited. I'm making a classic pong game and when I move my mouse out too fast, the 'thing' stays some pixels in. I'd like it to move to the edge of the window where it exited.

private class MouseMotion extends MouseAdapter{
    public void mouseMoved(MouseEvent e) {
        super.mouseMoved(e);
        int x = e.getX();
        p1.move(x);
    }
}

and the move function

public void move(int x) {
    if (x < 0  ) {
        this.x = 0;
    }else if(x+width > Main.screenSize.width - 1){
        this.x = Main.screenSize.width - width - 1;
    } else {
        this.x = x;
    }
}

I just need to know a way to know if the mouse is out of the window.

4

4 回答 4

4

检查MouseListener.mouseExited(MouseEvent).

于 2013-08-11T09:10:32.770 回答
2

你可能想看看这个:

Point mouse = MouseInfo.getPointerInfo().getLocation();

这告诉您指针在屏幕上。无论您的应用程序是否具有焦点。无论指针是否位于窗口顶部。

于 2013-08-11T09:32:33.523 回答
0

尝试将它放在可以运行的地方并摆脱 MouseMotion 类。'c' 是 p1 被吸引到的 JComponent,我不知道您在代码中称该对象是什么。'running' 是一些设置为 true 的布尔值。运行此代码时,p1 将根据鼠标移动,直到 'running' 设置为 false。

new Thread(()->{
    while(running) {
        p1.move(MouseInfo.getPointerInfo().getLocation().getX()-c.getLocationOnScreen());
    }
}).start();
于 2014-06-14T15:48:49.593 回答
0

您可以使用 MouseExited(),然后使用 event.getPoint() 从生成的事件中获取坐标。

于 2013-08-11T09:14:36.273 回答