如何使用esc或按钮Java终止程序 [英] How to kill a program with esc or a button Java

查看:343
本文介绍了如何使用esc或按钮Java终止程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的程序运行,但是一旦按esc退出程序.我能想到的唯一方法是做一个扫描仪,然后寻找下一行,但这会暂停整个程序.也许是关键的倾听者,但是我如何使其不断得到检查?它是一个GUI.任何帮助都会很棒!

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
}

推荐答案

如果您使用框架,则可以注册密钥.

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

这篇关于如何使用esc或按钮Java终止程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆