views:

397

answers:

5

I have a Java program where I have a JMenu with an arbitrary number of items (in this case, there is one menu item for each dynamic library currently loaded in a different program). I'm running a loop to add JCheckBoxMenuItem s to the menu, since I don't know how many there will be.

How can I set up an action listener for these menu items that is aware of which option called it? Specifically, I want to run the same function but with a different set or parameters for each of the menu items (and a different function again depending on whether the check is being toggled or detoggled).

Could someone point me in the right direction?

+1  A: 

event.getSource() should do it.

TofuBeer
+2  A: 

Definitely read over this: http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

In short, add ActionListener to the menuItems. In the actionPerformed method, use event.getSource(). You can add the SAME ActionListener to all your menu items if you want.

basszero
+1  A: 

When you build the menu you can pass the Action object to the JCheckBoxMenuItem configured with whatever options you need for given action (you can also push there the reference to the check box to check the state). This way you will not have to do any kind of processing when the action is actually performed, because the correct action will be invoked.

Bogdan
+1  A: 

While event.getSource() will definitely let you know which particular button the event came from it has the side effect of needing to track the generated buttons or snooping into the button. Also you may want to present a different name of the library to the user (possibly including the version information) than is used to identify the library. Using the "ActionCommand" property of the button may provide a way to separate those issues. So you will need to alter code in the generation of the checkbox menu items and in the listener.

ActionListener actionListener = ... // whatever object holds the method, possibly this
String[] libraries = ... // however you get your library names
JMenu parentMenu = ... // the menu you are adding them to

for (String s : libraries) {
  // prettyName is a method to make a pretty name, perhaps trimming off
  // the leading path
  JCheckBoxMenuItem child = new JCheckBoxMenuItem(prettyName(s), true);
  child.setActionCommand(s);
  parentMenu.acc(child);
}

The action handler code would be...

public void actionPerformed(ActionEvent evt) {
  // the 'current' selection state, i.e. what it is going to be after the event
  boolean selected = ((JCheckBoxMenuItem)evt.getSource()).isSelected();
  String library = evt.getActionCommand();
  ... process based on library and state here...
}
shemnon
A: 

The clean way to do it is to create a different ActionListener for each. EventObject.getSource is fugly.

Tom Hawtin - tackline
Sure, but then how would I call each ActionListener with parameters that are unknown at compile time?
Zxaos