Alright guys, so right now I'm working on a program that finds the current focused window and adds a KeyListener to it. The problem is that unlike when you have a window running and you add a KeyListener to it and it stays working until you close the window, once I add the KeyListener to the focused window my program ends. What I want to do is to keep it running, that way whenever a key is presses the mouse will make a click. Here is my code:

import java.awt.KeyboardFocusManager;
import java.awt.Robot;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TestClass implements KeyListener{

    private KeyboardFocusManager m;
    private Window w;

    public void setUp(){
            m = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            w = m.getFocusedWindow();
        }catch(Exception e){}
    public void keyPressed(KeyEvent event){
            Robot robot = new Robot();
            robot.delay((int) Math.random()*150);
        }catch(Exception e){}
    public void keyReleased(KeyEvent event){}
    public void keyTyped(KeyEvent event){}

    public static void main(String[] args){
        new TestClass().setUp();

Is there a way to listen to key events outside a window?

Edited 6 Years Ago by Zetlin: n/a


Is there a way to listen to key events outside a window?

As far as I now it is not possible to listen to even outside window using Java.
This could be done by using JNI .

This article has been dead for over six months. Start a new discussion instead.