thetypist
thetypist

Reputation: 333

Action performed upon keypress

I'm trying to simply print to the console when the letter 'a' is pressed using a KeyListener. Basically what happens when I run the program is that it opens and then closes. If I keep pressing keys it runs longer, but it doesn't print to the console. What's wrong with my code?

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class APresser implements KeyListener {

    private static int keyCode;

    public static void main(String[] args) {

    }

    public void aPressed(KeyEvent e) {
        keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_A) {
            System.out.println("A was pressed!");
        }
    }

    public void keyPressed(KeyEvent e) {

        aPressed(e);


    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

Upvotes: 1

Views: 1502

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

KeyListener is an interface of the AWT framework, it is intended to be used with GUI and can't be used for console based applications.

Detecting key presses in a console is not something Java does natively, you need to wait till the user presses the Enter

You can use a Curses library of some kind, but this brings with a integration into the native system which may limit the usefulness of your program

Equally, monitoring for keystrokes while the program does not have focus (in the background) is not something Java does either, you will need to resort to a JNI/JNA solution

Upvotes: 2

Related Questions