Another Java GUI question - use one JMenuBar on two JFrames?

notfred

Lifer
Feb 12, 2001
38,241
4
0
I want to use the same menu on two different JFrames, is here anyway to do this? I tried to jsut set the menubar in both Jframes, but only the last one assigned keepd the menu. Any help?
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
Not sure how to use the same menu object (I did a quick test and the menu does disappear like you noticed), but you can use the same function that creates a menu:

For the first JFrame:

(JFrameObject).setJMenuBar(createBar());

and for the second JFrame:

(JFrameObject).setJMenuBar(createBar());

Not quite as memory efficient, but you can reuse the code at least. If you want code examples, let me know.
 

manly

Lifer
Jan 25, 2000
12,764
3,561
136
I've never tried that, but just wrap the menu bar creation code behind a method that returns a new instance of JMenuBar.

You may also want to look into Actions, which connect a toolbar button and menu item together logically.

Working on a CS class project?
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
I'm working on a personal project (Although, I should be working on a CS class project, but CLI apps that do useless theoretical stuff get boring). Anyway, I want to be able to update both meubars at the same time, for example, if someone selects "Window > Show Editor" on the menu, it should then change that menu option to "Hide Editor" in all instances of the menu.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
You should be able to do it through ChangeEvents and ChangeListeners.

ChangeEvent

ChangeListener

Just have the menubars throw change events when the show/hide options are toggled, and set to listen for those change notices. It should be able to have one change filter through all the menubars that way.
 

manly

Lifer
Jan 25, 2000
12,764
3,561
136
From http://java.sun.com/products/jfc/tsc/articles/actions/:
Components which have been constructed from the same Action will share some properties such that the state of the components will be in sync with the state of the Action. For example, if the action becomes disabled, then all components which use that action will also be disabled. When a property on an action is changed, it fires a property change event. All components that have been constructed from that Action will have implemented a property change listener which will act on the event and change the state of the component.