How to detect a key press in Java

前端 未结 6 1642
野的像风
野的像风 2020-12-30 07:29

My son (aged 11) who is learning Java is going to enter a question and some code. He tells me he has not been able to find the answer to this question on the site. You will

6条回答
  •  灰色年华
    2020-12-30 08:30

    There's a great library which works smoothly and it listens to global events. It's the only thing which worked without any issues for me: https://github.com/kwhat/jnativehook

    It grabs every event in the system, pretty cool for any development.

    You can use it like this:

    package main;
    
    import org.jnativehook.GlobalScreen;
    import org.jnativehook.NativeHookException;
    import org.jnativehook.keyboard.NativeKeyEvent;
    import org.jnativehook.keyboard.NativeKeyListener;
    
    class MyKeyboard implements NativeKeyListener {
    
        public static void main(String[] args) {
            try {
                GlobalScreen.registerNativeHook();
            } catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());
    
                System.exit(1);
            }
    
            GlobalScreen.addNativeKeyListener(new MyKeyboard());
    
            // Now press any keys and look at the output
        }
    
        @Override
        public void nativeKeyPressed(NativeKeyEvent e) {
        }
    
        @Override
        public void nativeKeyTyped(NativeKeyEvent nke) {
        }
    
        @Override
        public void nativeKeyReleased(NativeKeyEvent nke) {
        }
    
    }
    

提交回复
热议问题