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);
}
}
1条答案
按热度按时间xuo3flqw1#
试试下面的例子