写一段java代码,可以体现javaswing中的MVC模式
时间: 2024-01-22 17:20:44 浏览: 86
Java的MVC模式样例
以下是一个简单的 Java Swing 中的 MVC 模式示例:
Model 类:
```java
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
View 类:
```java
public class StudentView extends JFrame {
private JTextField nameTextField;
private JTextField ageTextField;
private JButton saveButton;
public StudentView() {
JLabel nameLabel = new JLabel("Name:");
nameTextField = new JTextField(20);
JLabel ageLabel = new JLabel("Age:");
ageTextField = new JTextField(20);
saveButton = new JButton("Save");
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(nameLabel);
panel.add(nameTextField);
panel.add(ageLabel);
panel.add(ageTextField);
panel.add(saveButton);
add(panel);
setTitle("Student Information");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public String getName() {
return nameTextField.getText();
}
public void setName(String name) {
nameTextField.setText(name);
}
public int getAge() {
return Integer.parseInt(ageTextField.getText());
}
public void setAge(int age) {
ageTextField.setText(String.valueOf(age));
}
public void addSaveListener(ActionListener listener) {
saveButton.addActionListener(listener);
}
}
```
Controller 类:
```java
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view) {
this.model = model;
this.view = view;
view.setName(model.getName());
view.setAge(model.getAge());
view.addSaveListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveStudent();
}
});
}
private void saveStudent() {
model.setName(view.getName());
model.setAge(view.getAge());
JOptionPane.showMessageDialog(null, "Student information saved successfully.");
}
}
```
Main 类:
```java
public class Main {
public static void main(String[] args) {
Student model = new Student();
StudentView view = new StudentView();
new StudentController(model, view);
}
}
```
在这个例子中,`Student` 类是模型,`StudentView` 类是视图,`StudentController` 类是控制器。控制器将模型和视图连接在一起,处理视图中的用户输入并更新模型和视图。这个例子中的模型只有两个属性(姓名和年龄),但是可以添加更多的属性和方法。这是一个非常简单的示例,但是演示了如何使用 MVC 模式在 Java Swing 应用程序中进行开发。
阅读全文