如果不专注于JavaFX阶段,如何获得键盘输入?

我试图理解如何在不专注于JavaFX阶段的情况下获得键盘输入。 通常,当我想获得一个键输入时,我这样做:

public class Controller implements Initializable{ @FXML Button btn ; @FXML VBox vBox ; @Override public void initialize(URL location, ResourceBundle resources) { vBox.setOnKeyPressed(new EventHandler() { @Override public void handle(javafx.scene.input.KeyEvent event) { System.out.print(event.getCode()); } }); } } 

但是,当我不专注于我的程序时,如何获得输入?

使用纯Java是不可能的,因为Java在JVM中运行,您无法监听全局击键。

您可以使用像jnativehook这样的JNI库来执行您想要的任务。 我曾经在一个项目中使用过它,这很简单。 这里有一段代码片段:

 import org.jnativehook.GlobalScreen; import org.jnativehook.NativeHookException; import org.jnativehook.keyboard.NativeKeyEvent; import org.jnativehook.keyboard.NativeKeyListener; class Example implements NativeKeyListener { public static void main(String[] args) { new Example(); } public Example() { try { GlobalScreen.registerNativeHook(); } catch (NativeHookException e) { e.printStackTrace(); } GlobalScreen.addNativeKeyListener(this); } @Override public void nativeKeyPressed(NativeKeyEvent ev) { // check your specific key press here // example: if(ev.getKeyCode() == NativeKeyEvent.VC_H) { // the key "h" is pressed System.out.println("Hello!"); } } @Override public void nativeKeyReleased(NativeKeyEvent arg0) {} @Override public void nativeKeyTyped(NativeKeyEvent arg0) {} } 

你只需要将jnativehook-2.0.3.jar添加到你的构建路径中,你就可以了。

编辑:关于评论的简短而笨拙的例子。

 class Example implements NativeKeyListener { private Robot bot; private boolean ctrlPressed = false; private TextArea textArea1; private TextArea textArea2; // more TextAreas ... public Example(TextArea textArea1, TextArea textArea2) throws Exception { this.textArea1 = textArea1; this.textArea2 = textArea2; // ... bot = new Robot(); Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName()); logger.setLevel(Level.OFF); GlobalScreen.registerNativeHook(); GlobalScreen.addNativeKeyListener(this); } @Override public void nativeKeyPressed(NativeKeyEvent ev) { if(ev.getKeyCode() == NativeKeyEvent.VC_CONTROL_L) { ctrlPressed = true; // ctrl key is pressed } } @Override public void nativeKeyReleased(NativeKeyEvent ev) { if(ev.getKeyCode() == NativeKeyEvent.VC_CONTROL_L) { ctrlPressed = false; // ctrl key is released } if(ev.getKeyCode() == NativeKeyEvent.VC_1 && ctrlPressed) { // check if ctrl + 1 is used Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(textArea1.getText()); // adding content of textArea1 clipboard.setContents(stringSelection, stringSelection); // copy content to the system clipboard bot.keyPress(KeyEvent.VK_V); // use (ctrl+)v to paste current clipboard content bot.keyRelease(KeyEvent.VK_V); } if(ev.getKeyCode() == NativeKeyEvent.VC_2 && ctrlPressed) { // same as for ctrl+1 with the content of textArea2 } // further if statements for the different key combinations and text areas // .... } @Override public void nativeKeyTyped(NativeKeyEvent arg0) {} // irrelevant }