Luke Worthing
Luke Worthing

Reputation: 101

How to kill a program with esc or a button Java

I want my program to run but once esc is pressed to quit the program. The only way I can think of doing this is by doing a scanner and looking for the next line but that pauses the whole program. Maybe a key listener but how do I make it be constantly checking? And it is a GUI. Any help would be great!

static Scanner sc = new Scanner(System.in);

stop = sc.nextLine();

if (stop.equals(a)){
running = false;
}
else{
do program
}

Upvotes: 1

Views: 3535

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347294

If this is a UI, you should not be maintaining any kind of loop that could block the Event Dispatching Thread.

The EDT will dispatch key events to your program and you can respond to them if you have registered for notifications.

I would avoid KeyListener as it requires the component it is registered to be focused and have keyboard focus before it will respond.

Instead, I would use the Key Bindings API.

You can register a Escape key to either the main application window (or sub component) or directly with the JButton you are using to close the application with.

Upvotes: 1

nachokk
nachokk

Reputation: 14413

If u use a frame you can register the keys.

myFrame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "EXIT"); 
    myFrame.getRootPane().getActionMap().put("EXIT", new AbstractAction(){ 
        public void actionPerformed(ActionEvent e)
        {
            myFrame.dispose();
        }
    });

Upvotes: 2

Related Questions