【发布时间】:2019-04-28 13:14:46
【问题描述】:
我无法理解如何使用 JavaFX 应用 mvc 模式。
以下是我对以下代码的问题,因为我需要遵循代码中给出的模式:
a) 如何将 ViewA 中存在的按钮的事件处理程序附加到 ControllerA 中的代码(特别是 attachEventHandlers() 方法)。例如,我希望我的按钮使用来自控制器的getModelItems() 方法的结果填充 ViewA 中的组合框。
注意getModelItems() 方法是私有的。
b) 我的视图中有多个按钮和事件处理程序。我将如何将它们中的每一个唯一地绑定到控制器?
c) 我想在控制器中的模型上调用setName(String name),我要传递的参数是viewA 中comboBox 上的选定值。我怎样才能做到这一点?
非常感谢您的帮助!
下面是描述中提到的代码。
控制器:
import model.ModelA;
import view.ViewA;
public class ControllerA {
private ViewA view;
private ModelA model;
public ControllerA(ViewA view, ModelA model) {
//initialise model and view fields
this.model = model;
this.view = view;
//populate combobox in ViewB, e.g. if viewB represented your ViewB you could invoke the line below
//viewB.populateComboBoxWithCourses(setupAndRetrieveCourses());
this.attachEventHandlers();
}
private void attachEventHandlers() {
}
private String[] getModelItems() {
String[] it = new String[2];
it[0] = "0";
it[1] = "1";
return it;
}
}
型号:
public class ModelA {
private String name;
public Name() {
name = "";
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Name = " + name;
}
}
查看:
import javafx.scene.layout.BorderPane;
//You may change this class to extend another type if you wish
public class ViewA extends BorderPane {
public BorderPane bp;
public ViewA(){
this.bp = new BorderPane();
ComboBox comboBox = new ComboBox();
Button button1 = new Button("Populate");
bp.setTop(button1);
bp.setBottom(comboBox);
}
}
加载器:
public class ApplicationLoader extends Application {
private ViewA view;
@Override
public void init() {
//create model and view and pass their references to the controller
ModelA model = new ModelA();
view = new ViewA();
new ControllerA(view, model);
}
@Override
public void start(Stage stage) throws Exception {
//whilst you can set a min width and height (example shown below) for the stage window,
//you should not set a max width or height and the application should
//be able to be maximised to fill the screen and ideally behave sensibly when resized
stage.setMinWidth(530);
stage.setMinHeight(500);
stage.setTitle("Final Year Module Chooser Tool");
stage.setScene(new Scene(view));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
【问题讨论】:
标签: javafx model-view-controller