Faking ActionListeners

I was teaching a class last week, and someone asked me the following question:

"I've got a button that does the exact same thing as a menu item.  Can I just send an event that makes it look like the menu item was selected?"

After pondering for a minute, I tried the following and it worked!

Making  a fakeAction method

Create a method as follows:

public void fakeAction(Component c) {

    getToolkit().getSystemEventQueue().postEvent(

      new ActionEvent(c, ActionEvent.ACTION_PERFORMED, ""));

}            

(It's your choice if you want to explicitly qualify java.awt.event.ActionEvent or import it in your class.)

After you've defined this method, set up connections as you normally would for the menu action.  Then, for the button, connect its actionPerformed() event to the script fakeAction.  (Set up an event-to-script connection -- start the connection from the button's actionPerformed() event, end it on an empty spot in the design area, selecting event-to-script as the type of connection.

This connection will require a parameter.  Just connect the parameter c to the this property of the menu item that has the desired action.

This can apply to any two (or more) components that require the same action.

Generalizing

We can generalize this by putting this method into a class called something like Mimic.   I haven't written this yet, so I'll leave it as an exercise for the interested reader...

You may also want to start adding other methods into this for mimicking other events (like itemStateChanged and so on.)  You might also think about providing overloaded versions that take extra parameters so you can change the actions slightly.  For instance, a four-function calculator's number buttons all do nearly the same thing, just with a different number value.