读取键盘一次按一个键Java

ubof19bj  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(72)

如何在Java中从www.example.com中一次读取一个键System.in,而不需要用户按Enter键提交一行?
我已经试过搜索堆栈溢出了,没有找到任何东西...这是因为Java主要是一种现代的、以GUI为中心的语言,并假设我们希望通过事件来获取输入吗?

xuo3flqw

xuo3flqw1#

试试下面的例子

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);
    }
}

相关问题