views:

203

answers:

3

It seems to be well-known there is a bug when using JMenuItem.getRootPane(). I read the bug description but i cannot figure out a workaround. Do you know work-around code for this in an Action.actionPerformed() method ? Thank you.

Update: I get this now but that don't work with sub-menus :-(

 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);
  }
A: 

To get this workaround work with sub-menu, you'll need to add a another .getParent() Example: ((JPopupMenu)((JMenuItem)((JMenuItem)c).getParent()).getParent()).getInovker();

Nettogrof
+2  A: 

Interesting. You can't just keep using getParent() because each sub menu has its own popup menu. So you have to find all the menus in the chain until you find a JMenu with a JMenuBar as its parent. Then you can use that menu to look up the root pane. Something like this:

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;
}
camickr
+1  A: 

You might find it easier to initialize the Action with whatever it needs to work on, and if necessary to create separate action instances for each context (each window, or whatever). Certainly the code will be easier to read. :)

David Moles
I had this before but i don't think the code is significant easier to read and i cannot use the default Action contructor w/o arguments. Thank you.
PeterMmm