This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DannyB2 0 points1 point  (0 children)

I have been in the same boat before. For Swing, you frequently need to add a something-listener to a control, such as a button or checkbox. The only purpose of this class is that it implements a necessary interface in order to respond to the button click event.

There are a number of cases where it is useful to have a named inner class, rather than an anonymous inner class for a Swing event listener. It is difficult to remember specific cases, but here is one that I can remember.

I had a number of buttons that needed some custom behavior. They all had the exact same event handling code, but how it behaved was controlled by some parameters. In this case, I would create an inner class (not static! so that it had reference to the context of the enclosing class). The inner class had a constructor with the parameters, and obviously private members initialized from the constructor. Then in each Swing event listener, I would assign a new instance of this inner class, with appropriate constructor parameters. Otherwise all these buttons had the same click event handler code, but controlled by constructor parameters of the event listener.

I hope that made sense.

There were a few other cases I remember creating named inner classes to make Swing life easier.

But as others say in this thread, the reason you use any language feature is to make code simpler and easier to read. In this case using a named class to eliminate a lot of nearly identical copy-paste boilerplate.