English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I understand how to make an Action and map it to more than one component--in this case, I have it mapped to JButtons on a JToolBar and its corresponding same action to JMenuItems on a JMenu. I was wondering how I would be able to match its focus to one another.

To make clear what I mean:

Say there is a "Color" menu that you can tab to "Blue", "Red", and "Yellow", and also a "Color" toolbar that you can click on "Blue", "Red", and "Yellow". How would I use one Action for Blue that would know which I clicked on, and to set the corresponding focus on the opposite. In other words, if I click on "Blue" in the menu, the focus will stay there (with a radio button for instance). How do I make the "Blue" on the toolbar also get focus?

2007-10-26 22:34:30 · 3 answers · asked by Jean-Francois 5 in Computers & Internet Programming & Design

3 answers

have them both use the same Model. In Swing, everything has a "model" (which contains the actual "data" behind the component, have a look at the link in the source for more info). Both JButtons & JMenuItems have a "ButtonModel" as their model.

So for example, this would be:

ButtonModel blueModel = new DefaultButtonModel();

JButton blueBtn = new JButton("Blue");
blueBtn.setModel(blueModel);

JMenuItem blueMenu = new JRadioButtonMenuItem("Blue");
blueMenu.setModel(blueModel);

Now instead of adding an ActionListener to both JComponents, add a single one to the model:

model.addActionListener(...);

Hope this helps. If u have more questions, just ask me.

2007-10-27 05:46:43 · answer #1 · answered by Ben X 2 · 0 0

There are Ids for each components. So your action as to get these ids back.
Look for name of Id depending on the IDE you are using.
Once this is done it is quite easy to transfer focus to other component given the fact that you know which one generated the action and the name (id) of all you components.

2007-10-27 05:42:51 · answer #2 · answered by Otto 4 · 0 1

It would look something like this in your button HTML tags.

id="blueA"
onclick="javascript: myFunction(this.id)"

This passes the id "blueA" as a parameter to myFunction. You can decide what to do for each different button depending on the id that is passed.

You can also add the onclick attribute programmatically.

2007-10-27 09:17:53 · answer #3 · answered by Henry 5 · 0 1

fedest.com, questions and answers