package bugtest; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.KeyStroke; public class Main { public static void main(String[] args) { final JFrame jframe = new JFrame("Main Window"); jframe.getRootPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); jframe.getRootPane().add(new JLabel("Open dialog and try to close it using key ")); JButton openButton = new JButton("Open Dialog"); openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new TestDialog(jframe, "Test Dialog", true).setVisible(true); } }); jframe.getRootPane().add(openButton); jframe.setBounds(50, 100, 400, 100); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setVisible(true); } private static class TestDialog extends JDialog { public TestDialog(Frame owner, String title, boolean modal) { super(owner, title, modal); getRootPane().setLayout(new FlowLayout()); getRootPane().add(new Label("Close this dialog using key ")); JComboBox combo = new JComboBox<>(new String[]{"one", "two", "three"}); getRootPane().add(combo); getRootPane().add(new JTextField("Test")); combo.requestFocusInWindow(); setBounds(100, 150, 300, 100); setCloseWithEscape(); } private void setCloseWithEscape() { KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); Object actionKey = "cancel"; getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(k, actionKey); Action cancelAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent ev) { dispose(); } }; getRootPane().getActionMap().put(actionKey, cancelAction); } } }