Programming in Java
CBCS BHCS03 By Parul Chachra
Chapter 31
Introducing Swing
Reference: Schildt, H. Java: The Complete Reference. 7th ediEon. McGraw-
Hill EducaEon
The MVC Architecture
• By separaEng a component into a model, a view, and a controller, the specific
implementaEon of each can be changed without affecEng the other two
• For instance, different view implementaEons can render the same component in different ways without affecEng the model or the
controller
MVC Architecture
source: hQps://www.guru99.com/mvc-tutorial.html
Swing and MVC
• The high level of separaEon between the view and the controller in MVC is not beneficial for Swing components
• Instead, Swing uses a modified version of MVC that combines the view and the controller into a single logical enEty called the UI delegate.
• For this reason, Swing’s approach is called either the Model-Delegate architecture
• As the view (look) and controller (feel) are separate from the model, the look and feel can be changed without affecEng how the component is used within a program
Swing and MVC
• Most Swing components contain two objects.
• The first represents the model which is responsible for storing the state of the
component. Models are defined by interfaces
• The second represents the UI delegate which controls the display of the component and its event handling
• For example, the model for a buQon is defined by the Bu,onModel interface
• UI delegates are classes that inherit
ComponentUI. For example, the UI delegate for a buQon is Bu,onUI
Components and Containers
• A component is an independent visual control, such as a push buQon or slider
• A container holds a group of components.
• Furthermore, in order for a component to be displayed, it must be held within a container
• All Swing GUIs will have at least one container
• Because containers are components, a
container can also hold other containers. This enables Swing to define what is called a
containment hierarchy, at the top of which must be a top-level container.