2

大家好,

我只是想问一下是否可以JMenu.addSeparator()在调用后删除?例如,在我的表单中有一个菜单栏,在菜单栏中可以说有三个JmenuItems,每个都有JMenu.addSeparator()。我想要做的是,如果另一个用户正在登录,我想要setVisible(false)其中一个,JMenuItem因为那个特定的用户没有授权使用它JMenuItem。问题是当我setVisible(false)其中一个仍然存在时JMenuItemJMenu.addSeparator()看起来有点尴尬,因为两个中间没有JMenuItem存在JMenu.addSeparator()。希望你能帮我解决这个问题。提前致谢

4

2 回答 2

2

您有两种可能的解决方案...

你可以...

删除菜单的内容并根据用户可以执行的操作重新构建它...

menu.removeAll();
// Add menu items back in...
// Personally, I'd have some method that could return back all
// the JMenuItems that could appear on this menu based on the
// the user...

这将是我的首选解决方案...

你可以...

根据当前用户实际可以执行的操作隐藏/显示菜单项,然后删除JSeparator彼此相邻的所有 s,例如...

Component last = null;
for (Component comp : menu.getComponents()) {
    if (comp instanceof JSeparator && last instanceof JSeparator) {
        menu.remove(comp);
    } else {
        last = comp;
    }
}

就个人而言,我知道我更喜欢哪个,并且通常会产生一致的结果......

于 2014-02-13T02:20:06.783 回答
0

我遇到了必须从现有菜单中删除分隔符的情况。(旧代码,不允许重构整个混乱。)

所以我使用了 MadProgrammer 的第二个解决方案的想法 - 但将其重写为实际工作。

        Component last = null;
        for (int idx = 0; (idx < m_fileMenu.getMenuComponentCount()); idx++) {
            Component comp = m_fileMenu.getMenuComponent(idx);
            if (comp instanceof JPopupMenu.Separator && last instanceof JPopupMenu.Separator) {
                m_fileMenu.remove(comp);
                idx--;
            } else {
                last = comp;
            }
        }
于 2014-06-12T21:25:59.207 回答