JDialog的ESC键关闭对话框

14年前

Java Swing 中处理JDialogESC键关闭对话框

 

同时也可以添加ENTER键动作,采用抽象方法,在子类中实现其功能

 

 

 

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

 

import javax.swing.JComponent;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JRootPane;

import javax.swing.KeyStroke;

 

public abstract class JDialog_Lyz extends JDialog {

 

    public JDialog_Lyz(JFrame owner, String title, boolean modal) {

       super(owner, title, modal);

    }

 

    public JDialog_Lyz(JDialog owner, String title, boolean modal) {

       super(owner, title, modal);

    }

   

   

    public abstract void enterEvent();//Enter 键事件处理

   

    protected JRootPane createRootPane() {

       /*

        * ESC

        */

       ActionListener actionListener_Esc = new ActionListener() {

           public void actionPerformed(ActionEvent actionEvent) {

              dispose();

           }

       };

       /*

        * Enter

        */

       ActionListener actionListener_Enter = new ActionListener(){

           public void actionPerformed(ActionEvent e) {

              enterEvent();

           }

       };

       JRootPane rootPane = new JRootPane();

       rootPane.registerKeyboardAction(actionListener_Esc, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),JComponent.WHEN_IN_FOCUSED_WINDOW);

       rootPane.registerKeyboardAction(actionListener_Enter, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),JComponent.WHEN_IN_FOCUSED_WINDOW);

       return rootPane;

    }

 

}