代码之家  ›  专栏  ›  技术社区  ›  PeterMmm

jmenuitem.getrootpane()解决方法?

  •  2
  • PeterMmm  · 技术社区  · 16 年前

    好像是 well-known 使用jmenuitem.getrootpane()时出现错误。 我读了错误描述,但我找不到解决方法。 你知道在action.actionPerformed()方法中解决这个问题的代码吗?

    更新 :我现在知道了,但这不适用于子菜单。

     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);
      }
    
    3 回复  |  直到 12 年前
        1
  •  2
  •   camickr    16 年前

    很有趣。不能一直使用getParent(),因为每个子菜单都有自己的弹出菜单。因此,在找到jmenubar作为其父菜单的jmenub之前,必须找到链中的所有菜单。然后可以使用该菜单查找根窗格。像这样的:

    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
  •  1
  •   David Moles paddy-p    16 年前

    您可能会发现初始化 Action 无论它需要处理什么,如果需要,为每个上下文(每个窗口或其他)创建单独的操作实例。当然,代码会更容易阅读。:)

        3
  •  0
  •   Nettogrof    16 年前

    若要使此解决方案与子菜单一起工作,需要添加另一个.getParent() 例子: ((jpopupmenu)((jmenuitem)((jmenuitem)c.getparent()).getparent()).getinovker();