package ngp.swing; import javax.swing.JButton; import javax.swing.ImageIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; public class MethodButton extends JButton { private Object myReceiver; private Method myMethod; public MethodButton (ImageIcon image, Object target, String methodName) { super(image); init(target, methodName); } public MethodButton (String title, Object target, String methodName) { super(title); init(target, methodName); } public void setMethod (Object target, String name) { try { myReceiver = target; myMethod = target.getClass().getDeclaredMethod(name, new Class[0]); } catch (Exception e) { myMethod = null; } } protected void init (Object target, String name) { setMethod(target, name); addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { try { if (myMethod != null) myMethod.invoke(myReceiver, new Object[0]); } catch (Exception e) { // do nothing } } }); } }