views:

161

answers:

5

Hi,

Imagine I'm making a simple Word Processor with Java Swing. I've got a set of Actions written to perform text justification. On the MenuBar I've got a menu:

View
  Left Justify
  Center Jusitfy
  Right Justify

This consists of JRadioButtonMenuItems and a ButtonGroup to ensure only one item is selected at any one time.

Also, imagine I've got an equivalent toolbar consisting of JToggleButtons and again a ButtonGroup to ensure only only button can be active at any one time.

The "Left Justify" JRadioButtonMenu and JToggleButton are initialised using the same Action, and so on with the other items.

My question is this: what is the best method for syncronizing the two groups? If I click "Right Justify" icon on the toolbar, I want the group in the Menu to be updated accordingly, and vice versa.

A: 

Take a look at the Mediator Design Pattern

Boris Pavlović
Thanks. But it does seem like an awful lot of refactoring required in order to apply this pattern. It seems that if I did this I'd have to code specifically for each of the items. I was hoping that there is a smarter way to determine this automatically given that the menu items and the toolbar items share the same actions.
arooaroo
+1  A: 

I after a lot of searching I found information here. Basically, you can add this to your action's actionPerformed method:

action.putValue(Action.SELECTED_KEY, Boolean.TRUE);

And this will do all the work for you!

Unfortunately the official Sun tutorials don't cover this aspect (or at least I didn't spot it), hence the difficulty in spotting such a simple approach to resolving my problem.

arooaroo
This only works in Java 6 though.
eugener
A: 

If you are using the Swing Actions the components should be disabled/enabled automatically if the action itself is. You can register yourself as a propertyListener to an action as well to monitor other changes. Look at http://java.sun.com/javase/6/docs/api/javax/swing/Action.html for detailed list of which properties are available.

willcodejavaforfood
+1  A: 

Observer pattern my friend. The menu bar observe the toolbar, and the toolbar observe the menu bar. They will both be observer and observable. Each one has his own listener which, on a change event, notify the observer (the other one) with the new value in parameter.

One of the great advantage of the observer pattern is that there is very low coupling, so you don't need a lot of refactoring to implement the linking, to modify it or to remove it in the future.

Silence
A: 

On the other hand (me again), you could just write 1 listener in an external class. A listener for the menu and for the toolbar. When 1 changes, the listener set them both to the new value.

Silence