JMenuItem.getRootPane () workaround?

There seems to be a known bug when using JMenuItem.getRootPane (). I have read the description of the error but cannot find a workaround for the problem. Did you know that this method works in the Action.actionPerformed () method?

Update . I am getting this now, but not working with the submenu.

 public void actionPerformed(ActionEvent e) {
        Component c = (Component) e.getSource();
        if (c instanceof JMenuItem) {
            c = ((JPopupMenu)((JMenuItem)c).getParent()).getInvoker();
        }

        Component z  = SwingUtilities.getRootPane(c);
  }

      

+2


source to share


3 answers


Interesting. You can't just use getParent () because each submenu has its own popup menu. So you need to find all menus in the chain until you find JMenu with JMenuBar as parent. Then you can use this menu to find the root bar. Something like that:



public JMenu getMenuBarMenu(JMenuItem item)
{
    JMenuItem menu = null;

    while (menu == null)
    {
        JPopupMenu popup = (JPopupMenu)item.getParent();
        item = (JMenuItem)popup.getInvoker();

        if (item.getParent() instanceof JMenuBar)
            menu = item;
    }

    return (JMenu)menu;
}

      

+2


source


You might find it easier to initialize Action

with what it's supposed to work on and create separate instances of the actions for each context (each window or whatever) if necessary. Of course, the code will be easier to read. :)



+1


source


To get this submenu workaround you need to add another .getParent () Example: ((JPopupMenu) ((JMenuItem) ((JMenuItem) with) .getParent ()) GetParent ().) GetInovker () ;.

0


source







All Articles