Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sync JMenu ButtonGroups with JToolbar ButtonGroups

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.

like image 612
arooaroo Avatar asked Oct 27 '22 02:10

arooaroo


1 Answers

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.

like image 89
arooaroo Avatar answered Nov 15 '22 04:11

arooaroo