Describe the MVC Connection. How is this design pattern implemented in Java Swing applications?
Answer:-
MVC Connection in Java Swing
MVC stands for Model-View-Controller. It is a design pattern used to separate the application logic into three interconnected components. This separation helps manage complexity, improves maintainability, and promotes reusability.
1. Components of MVC
| Component | Responsibility |
|---|---|
| Model | Manages data and business logic |
| View | Displays UI to the user |
| Controller | Handles user input and interacts with the model and view |
2. MVC in Java Swing
In Swing, MVC is partially implemented internally. Swing components like JTable, JList, JTree use MVC, where:
- Model handles data (e.g.,
TableModel,ListModel) - View is the visual component (e.g.,
JTable,JList) - Controller is often implicit (event listeners)
However, you can also explicitly implement MVC in custom applications.
3. MVC Example: Simple Login Window
Model (Logic)
public class LoginModel {
public boolean authenticate(String username, String password) {
return username.equals("admin") && password.equals("1234");
}
}
View (UI)
import javax.swing.*;
public class LoginView extends JFrame {
JTextField usernameField = new JTextField(10);
JPasswordField passwordField = new JPasswordField(10);
JButton loginButton = new JButton("Login");
JLabel resultLabel = new JLabel();
public LoginView() {
setTitle("Login");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 150);
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(new JLabel("Username:"));
add(usernameField);
add(new JLabel("Password:"));
add(passwordField);
add(loginButton);
add(resultLabel);
setVisible(true);
}
}
Controller (Glue Logic)
import java.awt.event.*;
public class LoginController {
public LoginController(LoginView view, LoginModel model) {
view.loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String user = view.usernameField.getText();
String pass = new String(view.passwordField.getPassword());
if (model.authenticate(user, pass)) {
view.resultLabel.setText("Login successful!");
} else {
view.resultLabel.setText("Invalid credentials.");
}
}
});
}
}
Main Class to Run
public class MVCDemo {
public static void main(String[] args) {
LoginView view = new LoginView();
LoginModel model = new LoginModel();
new LoginController(view, model);
}
}
Summary of MVC in Swing
- Model = business logic and data
- View = UI components (Swing widgets)
- Controller = connects user actions to model and updates the view
