Getting the Currently Selected Menu or Menu Item : MenuSelectionManager « Swing « Java Tutorial






import java.awt.Component;

import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    MenuElement[] path = MenuSelectionManager.defaultManager()
        .getSelectedPath();

    if (path.length == 0) {
      System.out.println("No menus are opened or menu items selected"); 
    }
    for (int i = 0; i < path.length; i++) {
      Component c = path[i].getComponent();

      if (c instanceof JMenuItem) {
        JMenuItem mi = (JMenuItem) c;
        String label = mi.getText();
      }
    }
  }
}








14.28.MenuSelectionManager
14.28.1.Using MenuSelectionManager to determine the current selection path.Using MenuSelectionManager to determine the current selection path.
14.28.2.Getting the Currently Selected Menu or Menu Item
14.28.3.Create a change listener and register with the menu selection manager
14.28.4.Listening for Changes to the Currently Selected Menu or Menu Item