The practical problem was solved, it seems (see Mark Peters' and jjnguy's answers). And the fireActionPerformed
method was also already mentioned (see OscarRyz' answer), for avoiding potential concurrency problems.
What I wanted to add was that you can call all private and protected methods (including fireActionPerformed
), without the need to subclass any classes, using reflection. First, you get the reflection Method
object of a private or protected method with method = clazz.getDeclaredMethod()
(clazz
needs to be the Class
object of th class that declares the method, not one of its subclasses (i.e. AbstractButton.class
for the method fireActionPerformed
, not JButton.class
)). Then, you call method.setAccessible(true)
to suppress the IllegalAccessException
s that will otherwise occur when trying to access private or protected methods/fields. Finally, you call method.invoke()
.
I do not know enough about reflection, however, to be able to list the drawbacks of using reflection. They exist, though, according to the Reflection API trail (see section "Drawbacks of Reflection").
Here some working code:
// ButtonFireAction.java
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
public class ButtonFireAction
{
public static void main(String[] args) throws ReflectiveOperationException
{
JButton button = new JButton("action command");
Class<AbstractButton> abstractClass = AbstractButton.class;
Method fireMethod;
// signature: public ActionEvent(Object source, int id, String command)
ActionEvent myActionEvent = new ActionEvent(button,
ActionEvent.ACTION_PERFORMED,
button.getActionCommand());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
}
});
// get the Method object of protected method fireActionPerformed
fireMethod = abstractClass.getDeclaredMethod("fireActionPerformed",
ActionEvent.class);
// set accessible, so that no IllegalAccessException is thrown when
// calling invoke()
fireMethod.setAccessible(true);
// signature: invoke(Object obj, Object... args)
fireMethod.invoke(button,myActionEvent);
}
}