怎么样为JFrame和JDialog等窗口部件添加缺省按钮响应Escape键盘事件?
怎么样为JFrame和JDialog等窗口部件添加缺省按钮响应Escape键盘事件?
JFrame和JDialog都实现了RootPaneContainer接口,可以通过取得RootPane来实现。public class RootPaneHelper {
private RootPaneHelper() {
}
/**
*为RootPaneContainer组件设置缺省按钮,
*并添加Escape事件响应
*/
public static void decorate(RootPaneContainer rpc,JButton defaultButton,Action escapeListener){
JRootPane rp=rpc.getRootPane();
rp.setDefaultButton(defaultButton);
KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
InputMap inputMap = rp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(stroke, "ESCAPE");
rp.getActionMap().put("ESCAPE", escapeListener);
}
/**
*为RootPaneContainer组件设置缺省按钮,
*并添加Escape的默认事件响应:关闭窗口
*/
public static void decorate(final RootPaneContainer rpc,JButton defaultButton){
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
((Component)rpc).setVisible(false);
}
};
decorate(rpc,defaultButton,action);
}
}