使用MVC模式写一个java的swing代码
时间: 2024-02-24 12:58:24 浏览: 105
Java-Swing-MVC使用
好的,这是一个简单的使用MVC模式写的Java Swing代码示例:
Model.java:
```java
public class Model {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
```
View.java:
```java
import javax.swing.*;
public class View {
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private Model model;
public View(Model model) {
this.model = model;
frame = new JFrame("MVC Demo");
panel = new JPanel();
label = new JLabel(model.getText());
button = new JButton("Click me!");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void update() {
label.setText(model.getText());
}
public JButton getButton() {
return button;
}
}
```
Controller.java:
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
private Model model;
private View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
view.getButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.setText("Button clicked!");
view.update();
}
});
}
}
```
Main.java:
```java
public class Main {
public static void main(String[] args) {
Model model = new Model();
View view = new View(model);
Controller controller = new Controller(model, view);
}
}
```
这个简单的程序演示了MVC模式的基本实现,其中Model表示数据,View表示视图,Controller表示控制器,它们之间通过观察者模式进行通信。当用户点击View中的按钮时,Controller会更新Model的数据,并通知View进行更新。
阅读全文