javajarnoclassdeffounderrorjnativehook

JNativeHook Class not found


I needed a KeyListener which also works outside a focused GUI component, so after performing research I came across the JNativeHook library. But as soon as I downloadet the ZIB file (from here) and added the jnativehook-2.1.0.jar to my Eclipse project (Properties -> Java Build Path -> Libraries -> Add External Jar) a Error message occurs while running a testprogramm.

Error: Could not find or load main class key.GlobalKeyListenerExample Caused by: java.lang.NoClassDefFoundError: org/jnativehook/keyboard/NativeKeyListener

This is the first time where I use a external Jar, so I wanted to ask if I did something wrong, or what I need to do to solve this Problem.

My Program:

package key;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class GlobalKeyListenerExample implements NativeKeyListener {
    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
            try {
                GlobalScreen.unregisterNativeHook();
            } catch (NativeHookException e1) {
                
                e1.printStackTrace();
            }
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }

    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 GlobalKeyListenerExample());
    }
}

Solution

  • I've experienced the same problem.

    The solution for me was to put the JNativeHook.jar in the classpath, instead of the modulepath.