gpt4 book ai didi

java - 机器人类 - 如果按下按钮?

转载 作者:行者123 更新时间:2023-11-30 04:17:06 25 4
gpt4 key购买 nike

我已经阅读并理解了java中的Robot类是如何工作的。我唯一想问的是,如何在 if 语句内按下并释放鼠标按钮。例如,仅当按下/释放空格按钮(以及紧随其后)时,我才会进行单击。我会使用代码:

try {
Robot robot = new Robot();
if (/*insert my statement here*/) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e) {}

最佳答案

不幸的是,没有一种方法可以直接控制硬件(嗯,事实上有,但你必须使用 JNI/JNA),这意味着你不能简单地检查如果按下某个键。

您可以使用KeyBindings要将空格键绑定(bind)到操作,当按下空格键时,您将一个标志设置为 true,当松开空格键时,您将该标志设置为 false。为了使用此解决方案,您的应用程序必须是 GUI 应用程序,这不适用于控制台应用程序。

Action pressedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
spaceBarPressed = true;
}
};

Action releasedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
spaceBarPressed = false;
}
};

oneOfYourComponents.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "pressed");
oneOfYourComponents.getInputMap().put(KeyStroke.getKeyStroke("released SPACE"), "released");
oneOfYourComponents.getActionMap().put("pressed", pressedAction);
oneOfYourComponents.getActionMap().put("released", releasedAction);

然后,使用

try {
Robot robot = new Robot();
if (spaceBarPressed) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {
//handle the exception here
}
}
} catch (AWTException e) {
//handle the exception here
}

正如 GGrec 所写,更好的方法是在触发键盘事件时直接执行鼠标按下:

Action pressedAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {
//handle the exception here
}
}
};

关于java - 机器人类 - 如果按下按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18105736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com