使用Swing进行GUI开发.
我有一个自定义对话框,用于选择要在我的应用程序中打开的文件; 它的类扩展javax.swing.JDialog
并包含一个JFileChooser
可以切换显示或隐藏的组件,以及其他组件.
该JFileChooser
组件已处理本身ESC键:当显示的文件选择器(嵌入在我的对话),我按ESC键,文件选择隐藏自己.
现在我希望我的对话框也能这样做:当我按下ESC时,我想要关闭对话框.请注意,当显示嵌入式文件选择器时,ESC键应该只隐藏它.
有任何想法吗 ?
您可以使用以下代码段.这是更好的,因为rootPane将从对话框中的任何组件获取事件.如果需要,可以用dispose()替换setVisible(false).
public static void addEscapeListener(final JDialog dialog) { ActionListener escListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }; dialog.getRootPane().registerKeyboardAction(escListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); }
使用InputMap
和ActionMap
处理Swing中的关键操作.要干净地关闭对话框,请向其发送窗口关闭事件.
从我的博客:
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 ); }
如果您正在寻找使用Java 8新功能的技术,请尝试使用lambda表达式:
dialog.getRootPane().registerKeyboardAction(e -> { window.dispose(); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
要么
KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); int w = JComponent.WHEN_IN_FOCUSED_WINDOW; dialog.getRootPane().registerKeyboardAction(e -> window.dispose(), k, w);