On Linux/Unix
With a bit of help from this page:
// Setting console to raw mode
String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();
// Getting input stream
Console console = System.console();
Reader reader = console.reader();
// Checking if input is ^C
char c=0;
while(c!=3) { // 3 = ^C
c=(char)reader.read();
}
// ^C is entered
// Reset console to normal mode
cmd = new String[] {"/bin/sh", "-c", "stty sane </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();
// Initialize frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(3);
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setTitle("Why are you leaving me ?");
frame.setVisible(true);
On Windows/Macintosh
It doesn't seem to be possible with Java's own libraries. JLine could work as described here with this code:
ConsoleReader reader = new ConsoleReader();
char c=0;
while(c!=3) {
c=(char)reader.readVirtualKey();
}
// Frame stuff here
I think the comments explain everything you need. If not, let me know!
Sidenote: If you run this in Eclipse you'll get an NPE at Reader reader=console.reader()
, because that's the way Eclipse runs its programs; without a console.