How to kill a program with esc or a button Java

杀马特。学长 韩版系。学妹 提交于 2019-12-11 05:43:26

问题


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
}

回答1:


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();
        }
    });



回答2:


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.



来源:https://stackoverflow.com/questions/17034798/how-to-kill-a-program-with-esc-or-a-button-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!