Mega Code Archive

 
Categories / Java / Swing JFC
 

Dialog can be closed by pressing the escape key

//   TDialog //   Copyright (C) by Andrea Carboni. //   This file may be distributed under the terms of the LGPL license. // import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JRootPane; import javax.swing.KeyStroke; /** This dialog can be closed by pressing the escape key   */ public class TDialog extends JDialog {   private boolean bCancel;   //---------------------------------------------------------------------------   public TDialog(Frame f, String title, boolean modal)   {     super(f, title, modal);     bCancel = false;     addWindowListener(new WindowAdapter()       {         public void windowClosing(WindowEvent e)         {           bCancel = true;         }       }     );   }   //---------------------------------------------------------------------------   protected JRootPane createRootPane()   {     ActionListener al = new ActionListener()     {       public void actionPerformed(ActionEvent ae)       {         hide();         bCancel = true;       }     };     KeyStroke stroke   = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);     JRootPane rootPane = super.createRootPane();     rootPane.registerKeyboardAction(al, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);     return rootPane;   }   //---------------------------------------------------------------------------   /** Packs the dialog, centers it on its parent, shows it and disposes it on exit     */   public void showDialog()   {     bCancel = false;     pack();     setLocationRelativeTo(getParent());     show();   }   //---------------------------------------------------------------------------   public void setCancelled()   {     bCancel = true;   }   //---------------------------------------------------------------------------   public void clearCancelled()   {     bCancel = false;   }   //---------------------------------------------------------------------------   public boolean isCancelled()   {     return bCancel;   } }