Typically when I'm creating a Swing (or any UI) application, I have various Actions that appear on menu items and buttons. I usually create an action registry and store the actions in there and then when certain things occur, I disable/enable actions in the registry based on the state of the application. I wouldn't call myself an avid Swing developer, although I know my way around it well enough, but is this a pretty typical pattern for managing Actions? Or is there a more standard way of doing it?
thanks,
Jeff
I'm using annotations on actions, then finding them reflectively.
A bit tidier, and new actions get managed automatically.
From my experience, the 'most' standard way of handling actions performed on a Swing GUI is to create
ActionListener
s and have them handleActionEvent
s directly for the components with which they are registered. It is a simple design and it follows convention with other sorts of GUI events in the Swing framework (MouseListener
/MouseEvent
,TableModelListener
/TableModelEvent
, etc).The
Action
framework you describe is a powerful tool to allow for sharing of actions between many input methods (ie, having a toolbar button and menu item perform the same action, and therefore sharing the sameObject
for handling the events triggered by both, etc.). This abstraction is pretty cool, but Sun cautions that it is a bit heavier-weighted than the simple Observers. From theAction
JavaDoc:Jeff, your approach seems like a good approach. I do the same thing. I call the registry ActionHandler and it looks like this:
Now to disable, say ZoomAction, I use
I usually take the following approach:
Action
with the containingComponent
's action map.String
constant allowing the application bootstrap code to "pull out" theAction
from theComponent
in required (e.g. to add it to aJToolBar
,JMenuBar
, etc.).updateActionStates()
method within theComponent
, which is called when the user performs some action (e.g. selects N rows from aJTable
). This method enables / disables all bespoke actions based on the current state of theComponent
.Example:
Incidentally, I typically prefer
Action
s toActionListener
s for exposingAction
s that form part of myComponent
's API. For Actions that merely exist within theComponent
(e.g. a dialog's "Clear" button) I typically useActionListener
. However, I disagree with akf aboutActionListener
being the most standard approach - This may be true of smaller GUIs but not more complex Swing applications.