To add another stick to this fire, I prefer to use AbstractActions as an anonymous inner class, or more often as a standalone stand-alone class:
JButton myExitButton = new JButton(new MyExitAction());
As an example, the Control class, which is part of my MVC Swing project, has this as part of its code:
public class Control { // these two types below are interfaces private Model model; private View view; public Control(Model model, View view) { this.model = model; this.view = view; addViewListeners(); } private void addViewListeners() { view.setGetPageAction(new GetPageAction(this, "Get Page", KeyEvent.VK_G)); view.setSetTnRendererBtnAction(new SetTnRendererBtnAction(this, "Show Images", KeyEvent.VK_S)); view.setClearThumbNailsAction(new ClearThumbNailsAction(this, "Clear ThumbNails", KeyEvent.VK_C)); view.setSetDestinationAction(new SetDestinationAction(this, "Set Destination", KeyEvent.VK_T)); view.setDownloadAction(new DownloadAction(this, "Download", KeyEvent.VK_D)); view.setExitAction(new ExitAction(this, "Exit", KeyEvent.VK_X)); model.addPropertyChangeListener(new ModelListener()); } public View getView() { return view; } public Model getModel() { return model; } // ..... }
And the abstract class that underlies all my AbstractActions looks like this:
public abstract class MyAbstractAction extends AbstractAction { protected Control control; protected Model model; protected View view; public MyAbstractAction(Control control, String txt, int mnemonic) { super(txt); putValue(MNEMONIC_KEY, mnemonic); this.control = control; this.model = control.getModel(); this.view = control.getView(); } }
One caveat: note that I am not a professional programmer, but rather a hobby, therefore, although my ideas work for me, they cannot represent the absolute best in this area. All corrections and tips are welcome. The weakness of my design above is that I think that I "enter" my actions in an awkward way.