简体   繁体   English

如何用esc或Java按钮杀死程序

[英]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. 我想让我的程序运行但是一旦按下esc就退出该程序。 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. 它是一个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
}

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

If this is a UI, you should not be maintaining any kind of loop that could block the Event Dispatching Thread. 如果这是一个UI,则不应该维护任何可能阻止事件调度线程的循环。

The EDT will dispatch key events to your program and you can respond to them if you have registered for notifications. EDT会将关键事件发送到您的程序,如果您已注册通知,则可以回复它们。

I would avoid KeyListener as it requires the component it is registered to be focused and have keyboard focus before it will respond. 我会避免使用KeyListener因为它需要注册的组件被聚焦并且在响应之前具有键盘焦点。

Instead, I would use the Key Bindings API . 相反,我会使用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. 您可以将Escape键注册到主应用程序窗口(或子组件),也可以直接使用您用来关闭应用程序的JButton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM