I'm writing a small swing application to get to know the technology but i'm getting a bit fed up with doing Component.addActionListener(new Action....
[component refers to buttons,fields,labels etc]
I'm thinking of just having one class that implements all the listener classes i need and making this class a singleton that will handle all events. However when 10 different things need a mouseclick event I feel it's a bit untidy having 10 if-else blocks within the mouseClicked method. Any ideas?
many thanks in advance.
However when 10 different things need a mouseclick event I feel it's a bit untidy having 10 if-else blocks within the mouseClicked method.
You spotted the big drawback to your single listener proposal. One technique to clean up your listener code is to use an anonymous inner class as a listener and have it invoke a method:
IDE's that generate GUI code tend to use this technique, but since they can't generate meaningful method names the code they generate tends to be ugly and difficult to maintain.
It is also a good idea to group related GUI components/models/controllers together into a single component and encapsulate their many events into a few custom events. Then your main GUI controller deals with a couple high-level events rather than hundreds of ActionEvents. Check out this thread for more about that technique.
As for the annoymous inner class style, it just seems odd to be mixing my view code with my controller and operational logic, but i guess if the logic is encapsulated in separate classes and methods are called on instances within the inner class it should look ok. Maybe Swing shouldn't be described as implementing MVC but M[V+C]
Originally posted by Eddie Long:
Maybe Swing shouldn't be described as implementing MVC but M[V+C]
You are correct in that observation:
Although Swing's model architecture is sometimes referred to as a Model-View-Controller (MVC) design, it really isn't. Swing components are generally implemented so that the view and controller are indivisible, implemented by a single UI object provided by the look and feel. The Swing model architecture is more accurately described as a separable model architecture. If you're interested in learning more about the Swing model architecture, see A Swing Architecture Overview (outside of the tutorial), an article in The Swing Connection.
The Java Tutorial: Swing: Using Models