2013-07-01 49 views
1

當您單擊JMenu(或者當您單擊相鄰的JMenu,然後將鼠標拖到它上面時)時的默認行爲是展開並顯示其子菜單和菜單項。當這種情況(菜單展開時)發生時,我可以將其他行爲(如生成事件)關聯起來嗎?如何讓JMenu在展開時做些事情?

+1

自從測試以來,我已經刪除了我的答案,這是明顯的錯誤。抱歉。 –

+2

@ user2460978如果您想知道子菜單何時打開,那麼您需要將一個'PopupListener'附加到菜單'JPopupMenu'。查看'JMenu#getPopupMenu'作爲開始點。 – MadProgrammer

回答

3

有事件監聽器類專門爲JMenus:

javax.swing.event.MenuListener 

javax.swing.event.MenuDragMouseListener 

您需要調用以將這些關聯到組件的方法是

JMenuComponentName.addMenuListener(MenuListener m);JMenuComponentName.addMenuMouseDragListener(MenuDragMouseListener m);

3

您可以使用MenuListener這應該爲您提供有關菜單狀態的信息。

這個簡單的例子創建一個新的菜單項,每個菜單打開時...

import java.awt.BorderLayout; 
import java.awt.EventQueue; 
import javax.swing.JFrame; 
import javax.swing.JMenu; 
import javax.swing.JMenuBar; 
import javax.swing.JMenuItem; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.event.MenuEvent; 
import javax.swing.event.MenuListener; 

public class TestMenuBar { 

    public static void main(String[] args) { 
     new TestMenuBar(); 
    } 

    public TestMenuBar() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JMenuBar mb = new JMenuBar(); 
       JMenu main = new JMenu("Test"); 
       mb.add(main); 

       main.addMenuListener(new MenuListener() { 
        @Override 
        public void menuSelected(MenuEvent e) { 
         System.out.println("Selected"); 
         JMenu menu = (JMenu) e.getSource(); 

         menu.add(new JMenuItem("I'm dynamiclly created")); 
        } 

        @Override 
        public void menuDeselected(MenuEvent e) { 
         System.out.println("deselected"); 
        } 

        @Override 
        public void menuCanceled(MenuEvent e) { 
         System.out.println("Canceled"); 
        } 
       }); 

       JFrame frame = new JFrame("Testing"); 
       frame.setJMenuBar(mb); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.setSize(200, 200); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    }   
} 
相關問題