On OS X, users expect to be able to press Cmd-W to close a window.
Can I conf开发者_StackOverflow社区igure a JFrame to do this?
Typically, keybindings for the top-level windows are handled exclusively by the underlying OS. So on a Mac they should be already there, on a different system there is no meta key (? not sure, though, maybe has some simulation).
Anyway, you can add whatever additional keybinding you like to the JFrame's rootPane:
private void addMacCloseBinding(JFrame frame) {
frame.getRootPane().getActionMap().put("close-window", new CloseAction(frame));
frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("control W"), "close-window");
frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("meta W"), "close-window");
}
public class CloseAction extends AbstractAction {
private Window window;
public CloseAction(Window window) {
this.window = window;
}
@Override
public void actionPerformed(ActionEvent e) {
if (window == null) return;
window.dispatchEvent(new WindowEvent(
window, WindowEvent.WINDOW_CLOSING));
}
}
You should be able to specify the menu shortcut like this:
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.META_MASK));
精彩评论