You could use JNativeHook here is an example that prints every key and the number of keys pressed, you could modify this to your needs :-
import org.jnativehook.GlobalScreen;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Main implements NativeKeyListener
{
public static void main(String[] args)
{
try
{
GlobalScreen.registerNativeHook();
}
catch(Exception e)
{
e.printStackTrace();
}
GlobalScreen.getInstance().addNativeKeyListener(new Main());
}
private int count;
@Override
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Pressed " + NativeKeyEvent.getKeyText(e.getKeyCode()));
count++;
System.out.println(count);
}
@Override
public void nativeKeyReleased(NativeKeyEvent e)
{
}
@Override
public void nativeKeyTyped(NativeKeyEvent e)
{
}
}
If you do not know how to import the JNativeHook library then How to install JNativeHook Library?