How to have Command-W close a window on Mac OS in Java or Clojure
I'd like to have ⌘ + W close a window/JFrame
in a program I am writing in Clojure. How might this be accomplished? Pure Java solutions开发者_JAVA百科 are also welcome.
Here's one way:
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()));
Put that Action
in a menu on your menubar. The accelerator will be Ctrl + W on Windows.
Probably better would be to use the Keybinding API to have the main panel in each JFrame
(assuming there are multiple) bind the same KeyStroke
as above in its (WHEN_FOCUSED
) input map to an action in its action map that closes the frame.
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);
}
}
精彩评论