devxlogo

Capturing the ESCAPE Key Event

Capturing the ESCAPE Key Event

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist