2011-04-28 61 views

回答

3

通常,对于顶级窗口键绑定完全由底层操作系统来处理。因此,在Mac上,它们应该已经存在,在另一个系统上没有元键(不知道,但也许有一些模拟)。

无论如何,你可以添加你喜欢Jframe的的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)); 
    } 

} 
+0

谢谢 - 我不得不删除了'WHEN_ANCESTOR_OF_FOCUSED_COMPONENT'约束让它在我的特殊情况下工作(带一个JFrame JFreeChart ChartPanel作为其唯一的孩子),但除此之外,这完全是诀窍。 – Bill 2011-04-28 12:24:55

1

你应该能够说明这样的菜单快捷方式:

menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, 
         ActionEvent.META_MASK));