Sometimes we want to allow our user to make one action in many different ways. For example you can copy text in many different ways:
- Crtl + C
- Right mouse button → “Copy”
- Edit (in menu bar) → Copy
The result is always the same: selected text is in clipboard.
Action interface contains following methods:
void actionPerformed(ActionEvent event) // You should know this from ActionListener class. Triggers when given action is performed.
void setEnabled(boolean b) // This one enables and disables action...
boolean isEnabled() // ... while this one checks if action has been enabled or not. When action is not enabled then the option from menu bar is gray.
void putValue(String key, Object value)
Object getValue(String key)
void addPropertyChangeListener(PropertyChangeListener listener)
void removePropertyChangeListener(PropertyChangeListener listener)
putValue and getValue manages two things: name and value from action object. Action names’ can be found on oracle docs under “Field Summary”. For example:
action.putValue(Action.NAME, "Action name");
action.putValue(Action.SHORT_DESCRIPTION, "Short description of this action, which will be performed in tooltip box");
Last two methods can tell other objects about changes in Action object. For example, you can tell your menu bar that this action shouldn’t be available at some point. In result, the option in menu bar will become gray. Since those listeners are part of the JavaBean model, I’m not going to write more about it here, because this topic should, in my opinion, in “advanced” category.
Also, Action interface extends ActionListener class.
Keep in mind that Action is an interface. Each class that implements this interface must have all seven methods. Luckily, we also have AbstractAction class which implements all of the methods instead of one – actionPerformed. All you have to do is extend AbstractAction and define actionPerformed method.