2011-04-28 59 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));