用java对MVC模式的实现代码示例
时间: 2024-03-20 20:41:10 浏览: 66
以下是一个简单的 Java MVC 模式实现的示例代码:
Model 类:
```
public class Model {
private String data;
public void setData(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
```
View 类:
```
import java.awt.event.ActionListener;
import javax.swing.*;
public class View extends JFrame {
private JTextField textField = new JTextField(20);
private JButton button = new JButton("Click me");
public View() {
JPanel panel = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 100);
panel.add(textField);
panel.add(button);
this.add(panel);
}
public String getInput() {
return textField.getText();
}
public void setOutput(String text) {
JOptionPane.showMessageDialog(this, text);
}
public void addListener(ActionListener listener) {
button.addActionListener(listener);
}
}
```
Controller 类:
```
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.addListener(new ButtonListener());
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String input = view.getInput();
model.setData(input);
String output = "You entered: " + model.getData();
view.setOutput(output);
}
}
}
```
Main 类:
```
public class Main {
public static void main(String[] args) {
Model model = new Model();
View view = new View();
Controller controller = new Controller(model, view);
view.setVisible(true);
}
}
```
这个示例演示了一个简单的 MVC 模式实现,其中 Model 类表示数据模型,View 类表示用户界面,Controller 类作为控制器,将 Model 和 View 连接在一起,并处理用户输入。在这个例子中,用户在文本框中输入一些数据,然后单击按钮,将数据存储在 Model 中,并在输出框中显示。
阅读全文