Frage

Hello guys,

I just want to ask something if is it possible to remove JMenu.addSeparator() after it is being called? for example in my form there is a menu bar and inside the menu bar lets say there are three JmenuItems and each of it has JMenu.addSeparator(). What i want to do is, if a different user is log in I want to setVisible(false) one of JMenuItem because that particular user in not authorize to use that JMenuItem. The problem is when I setVisible(false) one of the JMenuItem the JMenu.addSeparator() still exist which kinda awkward to watch since there are no JMenuItem exist in the middle of two JMenu.addSeparator(). Hope you can help me with this problem. Thanks in advance

War es hilfreich?

Lösung

You have two possible solutions...

You Could...

Remove the contents of the menu and rebuilt it based on what the user can do...

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...

This would be my preferred solution...

You Could...

Hide/show the menu items based on what the current user can actually do and then remove all the JSeparators that appear next to each other, for example...

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

Personally, I know which I would prefer and generally, which would produce consistent results...

Andere Tipps

I ran into a situation where I had to remove the separator from an existing menu. (Old code and wasn't allowed to refactor the whole mess.)

So I used the idea of MadProgrammer's 2nd solution - but rewrote it to actually work.

        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;
            }
        }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top