I have a code running on the IntelliJ terminal, but I am required to exit the code by pressing the ESC key.
The whole program is designed to run on the command line but I understand that there is no way to implement what I want through the command line. I also understand that the best approach is to use KeyBindings, but I don't quite understand how to incorporate it in my code, so I am using the following KeyEvent to check if the key pressed was ESC and if so, then close/exit the program.
public class Pizzeria extends JFrame{
Pizzeria(PizzaFactory f) {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.out.println("Escaping..."); //does not print; is the IF statement wrong?
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
});
}
public static void main(String[] args) {
Pizzeria pizzaPatterns = new Pizzeria(new PizzaFactory());
System.out.println("Hello and welcome!");
// rest of my code, all CLI based
}
The problem is, this does not work when I press the escape key from the terminal. How do I fix this?
EDIT
I set the visibility to true before implementing the "close when ESC is pressed" thing. And it works, but only when the window is in focus. So I am still unsure how to make it interact with my CLI.
Pizzeria(PizzaFactory f) {
this.factory = f;
setVisible(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) { // handler
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.out.println("escaped ?");
System.exit(0);
}
}
});
}