我无法理解如何在JavaFX中应用mvc模式。
这是我对以下代码的疑问,因为我需要遵循代码中给出的模式:
a)如何将ViewA中存在的按钮的事件处理程序附加到ControllerA中的代码(特别是attachEventHandlers()
方法)。例如,我希望我的按钮使用来自控制器的getModelItems()
方法的结果填充ViewA中的comboBox。
请注意,方法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);
}
}
答案 0 :(得分:0)
您将委托添加到ViewA以允许访问:
public class ViewA extends BorderPane {
ComboBox comboBox;
Button button1;
public ViewA(){
comboBox = new ComboBox();
button1 = new Button("Populate");
setTop(button1);
setBottom(comboBox);
}
// Add delegates for all functionality you want to make available through ViewA
public ObservableList<String> getItems() { return comboBox.getItems(); }
public void setOnButton1Action(...) { ... }
public void setOnButton2Action(...) { ... }
...
}
您可以根据想要通过ViewA管理的数量来随意选择。