I have a thread which impelments JNativeHook.jar which creates a global keybourd and mouse listener. Based on user input the thread can act as such.
I would like to stop all Thread execution when a user (let's say) presses VK_SPACE. I would want to spawn another Thread which also watches the keyboard, and when it gets a VK_SPACE again it will tell the main Thread to resume.
Is this sort of action possible in Java, and how might it look?
Here is some code to work with and JNativeHook.jar
CODE:
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.VK_ESCAPE)
{
GlobalScreen.unregisterNativeHook();
}
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
WatchForMe w = new WatchForMe(this);
w.start();
this.wait();
}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
public static void main(String[] args)
{
try
{
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex)
{
System.err.println("There was a problem registering the native hook.");
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(new GlobalKeyListenerExample());
}
}
public class WatchForMe implements NativeKeyListener
{
boolean alive = true;
Thread me = null;
public WatchForMe(Thread me)
{
if(me == null) return;
this.me = me;
GlobalScreen.getInstance().addNativeKeyListener(this);
}
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
me.notify();
alive = false;
}
}
public void run()
{
while(alive){}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
}