Search code examples
javainputkeyboardkeylistenerrunnable

KeyListener not responding to keyboard input


I've been trying to learn more advanced java on my own (My class is only covering text files) and I'm stumped on the using KeyListener. I managed to get it to work in another program, but I can't find the problem here. No errors show up on the console. This program uses a robot to type predefined Strings in a text file. Here's the main class.

    import java.awt.AWTException;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    import javax.swing.SwingUtilities;


    public class FileTyper implements KeyListener {

static Keyboard kb;
static Scanner infile;
static boolean on = false;
static Window window;

public static void main(String args[]) throws AWTException, FileNotFoundException{
    init();
    start();
}
private static void init() throws AWTException, FileNotFoundException{
    window = new Window();
    kb = new Keyboard();
    kb.setSpeed(50);
    infile = new Scanner(new File("C:/Users/Ali/Desktop/input.txt"));

}
private static void start(){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {

            if(on && infile.hasNext()){
                String temp = infile.nextLine();
                kb.type(temp);
                kb.type("\n");
            }
        }
    });
}

@Override
public void keyPressed(KeyEvent e) {

}

@Override
public void keyReleased(KeyEvent e) {
    switch(e.getKeyCode()) {
    case KeyEvent.VK_F9:
        System.out.println("CONSOLE: Starting");
        on = true;
        break;
    case KeyEvent.VK_F10:
        System.out.println("CONSOLE: Stopping");
        on = false;
        break;
    }

}

@Override
public void keyTyped(KeyEvent e) {

}

}


Solution

    • For a KeyListener to work, you must first add it to a component via addKeyListener(...). You don't do this, and it won't work unless it has a chance to.
    • As camickr notes, a KeyListener requires that the component it listens to has focus.
    • Usually it's better not to use KeyListeners in Swing apps but to use Key Bindings.
    • Shoot, you don't even have a visible GUI of any kind at all, so you really need to do more studying of the tutorials to first get your gui up and running before even considering adding a KeyListener or use Key Bindings.

    Edit
    You state:

    What if I wanted to use KeyListener when the program window is minimized?
    I mean use a shortcut key to pause the start or stop the program

    Core Java by itself cannot do this. For this to work, you either need to augment Java with JNI or JNA or use an OS-specific utility program. I've used AutoIt for my Windows apps.