2014-08-29 52 views
1

我的程序有JMenuBarJMenuItem s。 他們有一個ActionListener,我設置了一個快捷方式setAccelerator。 現在我隱藏菜單欄,當窗口變得不專心時,爲顯示的圖像獲得更多空間。 但是在第一次隱藏菜單欄後,熱鍵停止工作。隱形JMenuBar,加速器不能正常工作

我該如何解決這個問題?

我創建了一個小例子代碼來說明這奇怪的行爲:

import javax.swing.*; 
import java.awt.event.*; 

class Example extends JFrame{ 
    public static void main(String[] args) { 
     new Example(); //main is static 
    } 
    static JMenuBar menubar; //be accessable for the ActionListener 
    Example() { 
     //JPanel 
     this.setSize(50,50); 
     this.setVisible(true); 

     //Menubar, static 
     menubar = new JMenuBar(); 
     this.setJMenuBar(menubar); 

     //Menu 
     JMenu filemenu = new JMenu("File"); 
     menubar.add(filemenu); 

     //Item 
     JMenuItem menuitem = new JMenuItem("Do Something..."); 
     filemenu.add(menuitem); 
     menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.SHIFT_DOWN_MASK)); // Shift + D 
     menuitem.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("Action!"); 
      } 
     }); 

     JButton button = new JButton("Show/Hide menubar"); 
     this.add(button); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("Toggle Bar!"); 
       menubar.setVisible(!menubar.isVisible()); //Toggle 
      } 
     }); 
    } 
} 

參考: 我使用Java 1.7.0_60-EA(Java 7中),在Mac上。 但是,這個錯誤獨立於使用Mac原生菜單欄或JFrame內的普通Java菜單欄而發生。

回答

1

您可以嘗試添加全局鍵綁定。如何添加鍵綁定解釋爲here

這裏是你可以做一個例子:

//Any component that is always visible in the window (like the image) 
JComponent c; 
//Get input and action map 
InputMap imap = c.getInputMap(WHEN_IN_FOCUSED_WINDOW); 
ActionMap amap = c.getActionMap(); 
//Put keybinding and action 
imap.put(KeyStroke.getKeyStroke("shift D"), "doSomething"); 
amap.put("doSomething", anAction); 

請注意,它只能在聚焦窗口。但是,無論菜單欄是否可見,都應該可以工作。