When you talk about defining an inner class for a GUI listener, I think immediately using anonymous classes to do the job:
newButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) {
You often see this, and I often use this in my own code.
Which one you use depends on the structure of your code, for example:
- how much work should each listener do
- how many codes are shared between handlers
If each handler is short (for example, only one method call, while all the real work is done in another class method), I will use anonymous classes. But it looks silly: unfortunately, java requires us to define an object to use the callback method.
It is also a matter of personal preference and coding style.
However, I rarely made a new top-level class for the GUI handler, as in your example: even if I separate the class to use one class for each button, I would define the class inside the class file that controls the buttons, either as a non-public top-level class, or as an internal (not anonymous) class. If the complexity of the GUI callback grows to such an extent that it deserves a separate class, I would start looking for places to refactor.
source share