Friday, November 4, 2011

How to close a JDialog with ESC key in java

Preamble 

This articles will show how to create a dialog which provides center to parent and ESC key functionality.

JDK and eclipse compatibility

JDK version 1.3 with eclipse 3.3 is the minimum requirement.

Project overview 

The downloadable zip file contains an eclipse project which has a MainFrame class for GUI. Clicking on the button will create a new parent centered Dialog with ESC functionality enabled. To close dialog press the ESC key.

Unzip the downloadable and load in the eclipse project. Make a run configuration for MainFrame class and you are all set.


Enjoy, if you like it please appreciate!
/**
  * Closes the dialog
  */
 protected void closeDialog() {
  this.setVisible(false);
  this.dispose();
 }
 
 //all the components are added to the root pane. This is the real magic.
 protected JRootPane createRootPane() {
  KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
  JRootPane rootPane = new JRootPane();
  rootPane.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
  return rootPane;
 }
 
 private ActionListener actionListener = new ActionListener() {
  
  public void actionPerformed(ActionEvent actionEvent) {
   closeDialog();
  }
 };