Swing Model-View-Controller
Developer's Cave July 25th. 2010, 8:49pm
It's old news that Java's Swing GUI toolkit follows a deficient Model-View-Controller (MVC) architecture. In most cases, Swing fuses together the notion of the View and Controller, but offers a separate Model. At least, that's what the naming convention implies. For example, JComboBox should be a View-Controller to a ComboBoxModel.
This particular case failed me today. In my situation, I have several JComboBox instances, all which should always offer the same contents (but each may have a different selection). The natural design is to have one ComboBoxModel serving all the JComboBox (View) instances.
Unfortunately, ComboBoxModel extends ListModel to include the current list selection as part of the Model. While I'm sure someone had a reason for this, this design decision binds the ComboBoxModel to the JComboBox View, wrecking any semblance of a proper MVC architecture.
The resulting behavior is to change the selection in every JComboBox instance when a selection is made in any one of them. That said, selection is not actually part of the View responsibility. (The View component of an MVC only displays the selection, and does not maintain it.)
Notice that JList and ListModel get it right by separating out the ListSelectionModel. To fix the problem for JComboBox, I've resorted to maintaining a separate ComboBoxModel for each JComboBox, populating them each with the full list of elements to be shown. When a new element is to be added to the Model, I add one to each ComboBoxModel instance.
Overall, Swing is a powerful and capable system, but I find myself learning its tricks and traps rather than focusing on my task at hand. I've coded several convenience classes to simplify Swing. Someday, time permitting, I'll codify them into a cleaner library.
Leave a Reply
You must be logged in to post a comment.













