我一直在研究 java 中的自动化,因为它是跨平台的,有点想为 linux 创建一个 autoit 替代方案。无论如何,我的脚本运行良好,但我只想能够使用热键切换操作。
我看过键绑定(bind)的文档 ( http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html ),但要么它不是我想要的,要么我误解了文档,在这种情况下请原谅我并指出我正确的地方方向。
我的问题是我没有运行 GUI,我有一个 java 程序每 3 秒将我的鼠标移动到一个新的随机位置。这是我的代码:
public static void main(String[] args) {
int[] screen = ScreenGetDim(); //get screen dimentions
while (1==1) {
int[] coordinates = new int[2]; //create an array for X and Y screen coordinates
coordinates[0] = IntGetRandom( 0, screen[0] ); //get random X coordinate on screen
coordinates[1] = IntGetRandom( 0, screen[1] ); //get random Y coordinate on screen
MouseMove(coordinates[0], coordinates[1]); //move the mouse to screen coordinates
Sleep(3000); //wait 3 seconds
}
}
这个脚本就像它应该的那样工作(ScreenGetDim()、IntGetRandom()、MouseMove() 和 Sleep( ) 都是可以完美运行的函数,而且我已经在代码的其他地方定义了这些函数。
我的目标是能够创建一个热键,当我在程序运行期间的任何时候按下它时,它就会执行某些操作。
例如,如果我可以将 F11 设置为热键,那么每次我按下它时都会执行 System.out.println("You pressed F11");
那就太好了。 例如,在 AutoIt 中,只需创建一个函数即可执行任何您想做的事情,我们称它为 Action(),然后您可以简单地执行 HotKeySet("{ F11}", "Action")
使 Action() 在您按 F11 时随时运行。我正在寻找 Java 的等价物。
感谢大家的帮助!
最佳答案
我认为您正在寻找事件处理。您需要实现 KeyListener 接口(interface),这样您就可以创建在您按下按钮时调用的函数,该函数将如下所示
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
//TODO list of all KeyCodes of events and code you want to execute(F11 keycode = 122)
}
}
之后您需要将 KeyListener 设置为监听您的界面,这里可能会有点棘手,因为我不知道您使用的是哪种 GUI。当我使用 KeyListeners 时,我使用了 Canvas,如果你正在使用它,它看起来像这样
canvas.addKeyListener(this);
希望这就是你要找的
关于java - 在 Java 中创建热键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486725/