ToB企服应用市场:ToB评测及商务社交产业平台

标题: javaFX为例的MVC案例 [打印本页]

作者: 美丽的神话    时间: 2024-6-11 19:22
标题: javaFX为例的MVC案例
实现 MVC(Model-View-Controller)模式通常涉及以下步骤:
  1. public class PersonModel {
  2.     private String name;
  3.     private int age;
  4.     public PersonModel(String name, int age) {
  5.         this.name = name;
  6.         this.age = age;
  7.     }
  8.     public String getName() {
  9.         return name;
  10.     }
  11.     public void setName(String name) {
  12.         this.name = name;
  13.     }
  14.     public int getAge() {
  15.         return age;
  16.     }
  17.     public void setAge(int age) {
  18.         this.age = age;
  19.     }
  20. }
复制代码
视图(View) - PersonView.java:
  1. import javafx.scene.control.Label;
  2. import javafx.scene.layout.VBox;
  3. public class PersonView extends VBox {
  4.     private Label nameLabel = new Label();
  5.     private Label ageLabel = new Label();
  6.     public PersonView() {
  7.         this.getChildren().addAll(nameLabel, ageLabel);
  8.     }
  9.     public void updateView(PersonModel person) {
  10.         nameLabel.setText("Name: " + person.getName());
  11.         ageLabel.setText("Age: " + person.getAge());
  12.     }
  13. }
复制代码
控制器(Controller) - PersonController.java:
  1. public class PersonController {
  2.     private PersonModel model;
  3.     private PersonView view;
  4.     public PersonController(PersonModel model, PersonView view) {
  5.         this.model = model;
  6.         this.view = view;
  7.         updateView();
  8.     }
  9.     public void setPersonName(String name) {
  10.         model.setName(name);
  11.         updateView();
  12.     }
  13.     public void setPersonAge(int age) {
  14.         model.setAge(age);
  15.         updateView();
  16.     }
  17.     private void updateView() {
  18.         view.updateView(model);
  19.     }
  20. }
复制代码
主应用步伐 - Main.java:
  1. import javafx.application.Application;
  2. import javafx.scene.Scene;
  3. import javafx.stage.Stage;
  4. public class Main extends Application {
  5.     @Override
  6.     public void start(Stage primaryStage) {
  7.         PersonModel model = new PersonModel("John Doe", 30);
  8.         PersonView view = new PersonView();
  9.         PersonController controller = new PersonController(model, view);
  10.         Scene scene = new Scene(view, 200, 100);
  11.         primaryStage.setTitle("MVC Example");
  12.         primaryStage.setScene(scene);
  13.         primaryStage.show();
  14.     }
  15.     public static void main(String[] args) {
  16.         launch(args);
  17.     }
  18. }
复制代码
在这个示例中,PersonModel 封装了姓名和年龄数据,PersonView 是一个简单的 GUI 视图,用于显示这些数据,而 PersonController 负责将模型和视图绑定在一起,并处理惩罚任何用户输入或模型更新。当 Main 应用步伐启动时,它会创建一个场景,其中包含视图,并将控制器和模型关联起来。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4