Swing:按下ESC键时如何关闭对话框? [英] Swing: how do I close a dialog when the ESC key is pressed?

查看:103
本文介绍了Swing:按下ESC键时如何关闭对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Swing开发GUI.

GUI development with Swing.

我有一个自定义对话框,用于选择要在我的应用程序中打开的文件;它的类扩展了 javax.swing.JDialog ,并包含一个 JFileChooser ,可以将其切换为显示或隐藏.

I have a custom dialog for choosing a file to be opened in my application; its class extends javax.swing.JDialog and contains, among other components, a JFileChooser, which can be toggled to be shown or hidden.

JFileChooser 组件已经可以单独处理ESC键:当显示文件选择器(嵌入在我的对话框中)并且按ESC时,文件选择器将隐藏自身.

The JFileChooser component already handles the ESC key by itself: when the file chooser is shown (embedded in my dialog) and I press ESC, the file chooser hides itself.

现在,我希望对话框执行相同操作:当我按ESC时,我希望对话框关闭.请注意,当显示嵌入式文件选择器时,按ESC键只能将其隐藏.

Now I would like my dialog to do the same: when I press ESC, I want the dialog to close. Mind you, when the embedded file chooser is shown, the ESC key should only hide it.

有什么想法吗?

推荐答案

使用 InputMap ActionMap 处理Swing中的关键动作.要干净地关闭对话框,请向其发送一个关闭窗口事件.

Use InputMap and ActionMap for dealing with key actions in Swing. To close the dialog cleanly, send a window closing event to it.

从我的博客:

private static final KeyStroke escapeStroke = 
    KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); 
public static final String dispatchWindowClosingActionMapKey = 
    "com.spodding.tackline.dispatch:WINDOW_CLOSING"; 
public static void installEscapeCloseOperation(final JDialog dialog) { 
    Action dispatchClosing = new AbstractAction() { 
        public void actionPerformed(ActionEvent event) { 
            dialog.dispatchEvent(new WindowEvent( 
                dialog, WindowEvent.WINDOW_CLOSING 
            )); 
        } 
    }; 
    JRootPane root = dialog.getRootPane(); 
    root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 
        escapeStroke, dispatchWindowClosingActionMapKey 
    ); 
    root.getActionMap().put( dispatchWindowClosingActionMapKey, dispatchClosing 
    ); 
}

这篇关于Swing:按下ESC键时如何关闭对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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