The naive way of writing building a menu in a Java Swing app is to do something like:
JMenu fileMenu = new JMenu('File'); JMenuItem openItem = new JMenuItem('Open...'); openItem.addActionListener(new ActionListener() { /* action listener stuff */ } ) fileMenu.addMenuItem(openItem);
A more experienced developer will recognize that actions can be accessed through a variety of mechanisms – menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:
Action openAction = new AbstractAction(); openAction.setName('Open...'); openAction.addActionListener(new ActionListener() { /* action listener stuff */ } ) ... JMenuItem openItem = new JMenuItem(openAction);
My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?
- Create a factory class that returns specific actions?
- Declare all of the actions as
private static final Actionin some utility class? - Take advantage of a Java application framework?
- Something else?
Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.
Swing Application Framework
This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state.
The website is worth the read.