14. 74. 3. 按Esc键隐藏JDialog is specify that pressing the Escape key cancels the dialog.

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;


public class EscapeDialogTest {
	public static void main(String[] a) {
	    EscapeDialog dlg = new EscapeDialog();
	    dlg.add(new JButton("按Esc键消失(隐藏)"));
	    dlg.setSize(300, 100);
	    dlg.setVisible(true);
	  }

}
class EscapeDialog extends JDialog{
	public EscapeDialog(){
		super((JFrame)null,false);
	}
	protected JRootPane createRootPane(){
		JRootPane rootPane = new JRootPane();
		KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
		Action actionListener = new AbstractAction() {
		      public void actionPerformed(ActionEvent actionEvent) {
		        System.out.println("关于消失...");//disappear:消失
		        setVisible(false);
		      }
		    };
		InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
		inputMap.put(stroke, "ESCAPE");
		rootPane.getActionMap().put("ESCAPE", actionListener);
		return rootPane;
	}
}



你可能感兴趣的:(14. 74. 3. 按Esc键隐藏JDialog is specify that pressing the Escape key cancels the dialog.)