Consider a scenario where a dialog is launched from a panel which itself was launched by another panel. It’s very tedious to get the dialog disposed when the ESCAPE key is pressed. The code segment below makes it easy to capture the ESCAPE key event, irrespective of the hierarchy, and performs the designated action.
//Has to be final because this instance is required in the inner class final UpdateCustomerData updationPanel = new UpdateCustomerData(mainPanel); //Setting the size updationPanel.setSize(400,150); //Creating an input map of the Root Pane InputMap map = updationPanel.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); //Adding the key that needs to be captured map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel" ); ActionMap actionMap = updationPanel.getRootPane().getActionMap(); //Creating the action that needs to be executed when the key is pressed Action close = new AbstractAction() { public void actionPerformed(ActionEvent ae) { updationPanel.dispose(); } }; actionMap.put( "cancel", close); //Displaying the Panel updationPanel.setVisible(true);
updationPanel is the panel that will be affected by the ESCAPE key event here.