Equivalent function to C's "_getch()" in Java?
Solution 1:
You could use the JLine library's ConsoleReader.readVirtualKey() method. See http://jline.sourceforge.net/apidocs/jline/ConsoleReader.html#readVirtualKey().
If you don't want to use a 3rd party library, and if you are on Mac OS X or UNIX, you can just take advantage of the same trick that JLine uses to be able to read individual characters: just execute the command "stty -icanon min 1" before running your program, and then System.in will no longer be line buffered and you can get an individual character using System.in.read(). Unfortunately, this trick doesn't work on Windows, so you would need to use a native library to help (or just use JLine).
Solution 2:
I found a code, Equivalent function to C's “_getch()
public static void getCh() {
final JFrame frame = new JFrame();
synchronized (frame) {
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
synchronized (frame) {
frame.setVisible(false);
frame.dispose();
frame.notify();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
});
frame.setVisible(true);
try {
frame.wait();
} catch (InterruptedException e1) {
}
}
}