class SomeClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// do something
}
}
If I have 4 buttons, do I really need to create 4 classes to handle each?
Is there no way to use a method in the current class instead?
You can use an anonymous inner class. For example:
An anonymous inner class has access to all the containing class’s methods and variables, including
privateones.Alternatively, you can create one
ActionListenerand register it for all four buttons. The downside to this is that you then need logic inside theActionListenerto figure out which button was pressed (assuming each button does something different):Note that this example still uses an anonymous inner class, but you can also use a named class if you prefer.
Finally, with Swing you can take advantage of the
Actionclass.Actions behave very much likeActionListeners but have several features that make GUI development easier in many cases.