简体   繁体   English

Java读取原始鼠标输入

[英]Java Read Raw Mouse Input

I'm looking for a way in Java to read in raw mouse input and not just the event listeners. 我正在寻找Java中读取原始鼠标输入而不只是事件监听器的方法。 I'll tell you what I'm doing. 我会告诉你我在做什么。 Essentially, there is a game where if you move the mouse to the right, I want Java to send key signals of the 'd' key being pushed down, and when the mouse is moved to the left, the 'a' key being held down. 本质上,有一个游戏,如果您将鼠标移至右侧,我希望Java发送按下“ d”键的键信号,而当鼠标移至左侧时,按住“ a”键下。 But, when you move the mouse, the game quickly corrects the mouse position and sends it right back into the middle of the screen. 但是,当您移动鼠标时,游戏会迅速纠正鼠标位置并将其发送回屏幕中间。 So, if you use mouse listener, you get one event of the mouse being moved to the right, then another quickly following of the mouse being move back to the left. 因此,如果您使用鼠标侦听器,则将鼠标移至右侧会发生一个事件,然后在鼠标移至左侧后又发生另一个事件。 I want to know if I can get data from the mouse without those corrections in the position. 我想知道是否可以在不进行位置校正的情况下从鼠标获取数据。 Thanks! 谢谢!

A little code might make the situation clearer, but here's what you can do. 少量的代码可能会使情况更加清晰,但是您可以执行以下操作。

While there are a number of APIs (LWJGL's Mouse interface, as one example) that allow you to directly poll the mouse position, it sounds like overprogramming in your case. 尽管有许多API(例如LWJGL的Mouse接口)可以直接轮询鼠标的位置,但听起来好像是在编程过度。 First, keep a private field with a reference to that last mouse position. 首先,保留一个私有字段,以引用该鼠标的最后位置。 We'll call it x here. 我们在这里称它为x

Use a MouseMotionListener, and have it call the same method from mouseMoved and mouseDragged . 使用MouseMotionListener,并从mouseMovedmouseDragged调用相同的方法。 That method should look something like this. 该方法应如下所示。

void controlMethod(MouseEvent event) {
    int newX = event.getXOnScreen();
    int dx = this.x - newX;
    if(dx > 0) **D Key Event**
    else if(dx < 0) ***A Key Event**

    x = newX;
}

That should do the job for you. 那应该为您完成工作。 The only thing you might want to look out for is the mouse straying off of the MouseMotionListener's area; 您可能要注意的唯一一件事是鼠标从MouseMotionListener所在的区域移开。 but there are always ways around things like that, and it seems a bit tangential. 但是总有一些方法可以解决此类问题,而且似乎有些切线。

As a final note, if you end up with wild swings in mouse control at the beginning of your game loop, consider setting the class field x to an Optional , and use Optional.ifPresent(...) for the dx logic. 最后要注意的是,如果在游戏循环开始时鼠标控制出现剧烈波动,请考虑将类字段x设置为Optional ,并对dx逻辑使用Optional.ifPresent(...) This will also protect you from data nullification, such as from a focus loss, and I recommend making it a practice. 这还将保护您免受数据无效(例如,由于焦点丢失)的影响,我建议您将其作为实践。

Best of luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM