Java读取原始鼠标输入 [英] Java Read Raw Mouse Input

查看:192
本文介绍了Java读取原始鼠标输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种Java读取原始鼠标输入的方法,而不仅仅是事件监听器.我会告诉你我在做什么.从本质上讲,有一个游戏,如果您将鼠标右移,我希望Java发送按下"d"键的键信号,而当鼠标向左移动时,按住"a"键下.但是,当您移动鼠标时,游戏会迅速纠正鼠标位置并将其发送回屏幕中间.因此,如果您使用鼠标侦听器,则将鼠标移到右侧会发生一个事件,然后在鼠标移回左侧时会迅速发生另一个事件.我想知道是否可以在不进行位置校正的情况下从鼠标获取数据.谢谢!

I'm looking for a way in Java to read in raw mouse input and not just the event listeners. 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. 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.

虽然有许多API(例如LWJGL的Mouse接口)可让您直接轮询鼠标位置,但听起来好像您的程序过度编程了.首先,保留一个私有字段,以引用该鼠标的最后位置.我们在这里将其称为x.

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. First, keep a private field with a reference to that last mouse position. We'll call it x here.

使用MouseMotionListener,并使其从mouseMovedmouseDragged调用相同的方法.该方法应如下所示.

Use a MouseMotionListener, and have it call the same method from mouseMoved and mouseDragged. 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;
}

那应该为您完成工作.您可能要注意的唯一一件事是鼠标从MouseMotionListener的区域移开;但是总有一些方法可以解决此类问题,而且似乎有点切线.

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; but there are always ways around things like that, and it seems a bit tangential.

最后一点,如果在游戏循环开始时鼠标控制摆幅大打折扣,请考虑将类字段x设置为Optional,并对dx使用Optional.ifPresent(...)逻辑.这还将保护您免受数据无效(例如,由于焦点丢失)的影响,我建议您将其作为一种实践.

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. This will also protect you from data nullification, such as from a focus loss, and I recommend making it a practice.

祝你好运!

这篇关于Java读取原始鼠标输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆