Search code examples
javaappletawtkeylistenerawtrobot

Java keypressed event not firing


During writing this code I realized if making into a jar there would have to be a graceful way to close the program. I have chosen to use the key 'F1'. I've researched a few articles online and found that the way I'm trying to handle it should be a viable approach, but the program doesn't even seem to fire the event method. The system.out.println never displays.

import java.applet.Applet;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;


public class MouseMove extends Applet implements KeyListener{

public static Random randomGenerator = new Random();
public static int code;

public void init(){
    addKeyListener(this);
}

public void keyPressed(KeyEvent evt){
    code = evt.getKeyCode();
    System.out.println("Key: "+KeyEvent.getKeyText(code));

    if(code == KeyEvent.VK_F1){
        System.exit(0);
    }
}

public void keyTyped(KeyEvent e){   
}
public void keyReleased(KeyEvent e){
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {

        Robot robot = new Robot();          

        while(true){

            robot.mouseMove((int)(Math.random()*1366), (int)(Math.random()*768));
            robot.delay(5000);
            robot.mouseWheel((int)(Math.random()*786));
            robot.delay(5000);
        }
    } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}//main

}//class

Solution

    1. KeyListener works only if Component has Focus in the Window.

    2. You have to create a visible Container.

    3. setFocusable() for Component

    4. Better would be use Swing JComponent.

    5. Use JFrame instead of JApplet.