I'm designing a P2P messaging application using Swing, and have been running into serious issues when it comes to organizing my GUI component ActionListeners. Each JButton and JTextField almost always needs its own ActionListener implementation designed, because each component naturally has a different effect on the application than the others. My immediate thought was to just use lambdas to define an actionPerformed() call for each unique component, but this becomes even more problematic, because lambdas cannot be passed any parameters from the caller (as far as I know) since we don't have any constructor to use as a passer. In short, it seems I have to choose between two options:
- Create a new class implementing
ActionListenerfor each component requiring unique action logic, cluttering my codebase to a preposterous degree (BUT allowing for parameter passing via said class's constructor/native methods). - Use an
actionPerformed()lambda for each component requiring unique action logic, streamlining my codebase while requiring a complete redesign of said logic's details due to the loss of parameter passing.
I would be stunned, however, if this bad choice road is the reality of the situation. Is there an alternative to these poor options? Maybe a programming paradigm I've entirely overlooked?
final. Here are a list of patterns that comes to mind and might help: Command, Strategy, Observer, Action/Input Map, Mediator and Factory. You can apply all or some it depends on your implementation details, which you left out of your question.finalwithout issue. Lambdas can also reference fields, which don't have to be (effectively) final. When an outside local variable or field is referenced inside a lambda, the lambda implementation captures the object. For instance fields, the captured object is the enclosingthis. For static fields, the lambda implementation just queries the field directly (no capturing).String str = "Hi"; Runnable r = () -> System.out.println(str);. The lambda has captured the object referenced bystr(i.e.,"Hi"). This is essentially the same as passingstrto a named class implementation ofRunnablevia a constructor.