0

How can I read keyboard presses one key at a time from System.in in Java without the user pressing enter to submit a line?

I have tried searching stack overflow already and haven't found anything... is this because Java is primarily a modern, GUI focused language and assumes that we will want to get input via events?

Thomas Cook
  • 4,371
  • 2
  • 25
  • 42
  • 1
    Do you want to read it exactly from `System.in`, or from the keyboard in a console application, or from the keyboard in a GUI application? – cyberbrain May 24 '23 at 16:42
  • https://stackoverflow.com/q/4531560/438992, https://stackoverflow.com/q/4608854/438992 – Dave Newton May 24 '23 at 16:43
  • Does this answer your question? [How to read a single char from the console in Java (as the user types it)?](https://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – cyberbrain May 24 '23 at 16:48
  • Hello, sorry for the slow reply. I don't think so, I am writing a java swing app – Thomas Cook May 24 '23 at 18:09
  • Ah wait...yea writing JNI bindings around curses, that could work, but quite a pain! – Thomas Cook May 24 '23 at 18:10
  • If you’re writing a Swing application, you probably want to get key events when the application window has focus, not from the terminal console, right? – VGR May 24 '23 at 18:33

1 Answers1

0

Try below example

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

public class KeyboardInputExample {

    public static void main(String[] args) {
        System.out.println("Press any key ('q' to quit):");
        startKeyboardInput();
    }

    public static void startKeyboardInput() {
        KeyListener keyListener = new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                // Not used in this example
            }

            @Override
            public void keyPressed(KeyEvent e) {
                char keyChar = e.getKeyChar();
                int keyCode = e.getKeyCode();

                System.out.println("Key Pressed: " + keyChar + " (KeyCode: " + keyCode + ")");

                if (keyChar == 'q') {
                    stopKeyboardInput();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                // Not used in this example
            }
        };

        // Add the key listener to the console input stream
        System.in.addKeyListener(keyListener);

        // Loop indefinitely to keep the program running until 'q' is pressed
        while (true) {
            // Delay to prevent high CPU usage
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void stopKeyboardInput() {
        System.out.println("Keyboard input stopped.");
        System.exit(0);
    }
}
Satyajit Bhatt
  • 211
  • 1
  • 7