Source Code : Dialog can be closed by pressing the escape key

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

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;
  }
}

   
    
    
    
  

Thank with us