Most Swing components have models. A button (JButton
), for example, has a model (a ButtonModel
object) that stores the button's state — what its keyboard mnemonic is, whether it's enabled, selected, or pressed, and so on. Some components have multiple models. A list (JList
), for example, uses a ListModel
to hold the list's contents, and a ListSelectionModel
to track the list's current selection.
You often don't need to know about the models that a component uses. For example, programs that use buttons usually deal directly with the JButton
object, and don't deal at all with the ButtonModel
object.
Why then do models exist? The biggest reason is that they give you flexibility in determining how data is stored and retrieved. For example, if you're designing a spreadsheet application that displays data in a sparsely populated table, you can create your own table model that is optimized for such use.
Models have other benefits, too. They mean that data isn't copied between a program's data structures and those of the Swing components. Also, models automatically propagate changes to all interested listeners, making it easy for the GUI to stay in sync with the data.[It’s very important] For example, to add items to a list you can invoke methods on the list model. When the model's data changes, the model fires events to the JList
and any other registered listeners, and the GUI is updated accordingly.
Also, use model to share the application data and sync state automatically between different components.
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, an article in The Swing Connection.
How to Use Models (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)