解决方法
这是一种方法:
Action closeWindow = new AbstractAction("Close Window") { @Override public void actionPerformed(ActionEvent e) { // window closing code here } }; closeWindow.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke( KeyEvent.VK_W,Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
把这个动作放在菜单上的菜单上.加速器将在Windows上为Ctrl W.
在每个JFrame(假设有多个)中使用Keybinding API可能会更好地将主面板绑定到其(WHEN_FOCUSED)输入映射中的相同KeyStroke,使其在关闭框架的动作映射中的操作.
public class ClosableWindow extends JFrame { public void setUp() { JPanel mainPanel = createMainPanel(); int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); KeyStroke closeKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,mask); mainPanel.getInputMap().put(closeKey,"closeWindow"); mainPanel.getActionMap().put("closeWindow",new AbstractAction("Close Window") { @Override public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); } }); getContentPane().add(mainPanel); } }