Switching out JMenuBar

I was having a stupid problem when trying to switch out JMenuBar in a Swing app. The use case is like this. Initially, when the app is started, it displays a single File->Login.. menu. After the user logs in, depending on the role, the menu structure should change. You would think the following will work:

JMenuBar newMenu = getNewMenuBar();
JFrame frame = appContext.getFrame();
frame.setJMenuBar( newMenu );

However, this was causing the app to hang arbitrarily. I tried setting the menu bar to null before setting the new one, tried removing the old one, tried to call invalidate() on JFrame, but no luck. Turns out that our old friend validate() needs to be invoked on the JFrame to get rid of the problem. I have been bitten by this problem before but it is so easy to miss. Thanks to Google and this site, I was able to solve it.

Finally, this worked:

frame.setJMenuBar( newMenu );

2 Responses

  1. Kevin
    Kevin September 2, 2004 at 10:37 am |

    How about JMenuBar.updateUI()? That always works for me.

    And why are you creating more than one menu bar. Just “redraw” your menu bar using the menu items/menus you need, removing those you dont. No reason to create several menu bar instances for specific needs. You can even create a dynamic Action setup where a given role is allowed different types of Actions, some shared, some specific, and built the menu bar from that.

  2. Raj Madhuram
    Raj Madhuram September 7, 2004 at 11:35 pm |


    Thanks for your suggestions. Your point is well taken. I could have done that by re-creating the entire menu bar, but it is one of those things which I thought I could re-use,

Leave a Reply