In the previous lesson we saw how to define inner classes.
Separate listeners for each event
As programs become more complex it can be helpful to define a separate listener class for each individual event rather than use just one listener to serve all.
Step 1
Rename ButtonListener to CenterButtonListener. The most effective way to do this is by right-clicking on the ButtonListener text on the inner class declaration and selecting Refactor | Rename. Then enter CenterButtonHandler in the New Name box and click Refactor. As well as renaming the inner class, NetBeans will automatically locate and find everywhere it is referenced and update those as well.
Step 2
Simplify the actionPerformed() method inside CenterButtonHandler to just output the text entered into nameField:
Step 3
Modify the call to addActionListener() against myButton5 to instantiate a new CenterButtonHandler object instead of specifying buttonListener:
Step 4
At the end of the source code enter another inner class to handle the west button:
Step 5
Modify the call to addActionListener() against myButton4 to instantiate a new WestButtonHandler object instead of specifying this:
Step 6
Remove the following statements from the constructor as they are no longer needed:
Step 7
Verify that the application works as before.
The complete source code for ExampleFrame should look as follows:
To handle the other buttons, you can follow the same pattern of defining an inner class and instantiating an object of that type to serve as the button's listener.
In the next series of lessons we will look at common GUI components.