这是我的项目的样子:
Main.FXML
EggView.FXML
MainController.java
public class MainController implements Initializable {
/***CONTROLS***/
@FXML private VBox _eggsContainer;
@FXML private Button _btnAddEgg;
@FXML private Button _btnPrintEggs;
@FXML private Button _btnBreakEggs;
@Override
public void initialize(URL location, ResourceBundle resources) {
_btnAddEgg.setOnMouseClicked(e -> {
doAddEgg();
});
_btnPrintEggs.setOnMouseClicked(e -> {
doPrintAllEggs();
});
_btnBreakEggs.setOnMouseClicked(e -> {
doBreakAllEggs();
});
}
// Add an egg to _eggsContainer
private void doAddEgg() {
HBox eggControl = null;
try {
eggControl = FXMLLoader.load(getClass().getResource("EggView.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
_eggsContainer.getChildren().add(eggControl);
}
private void doPrintAllEggs() {
// prints ID and Color of each egg in _eggsContainer
}
private void doBreakAllEggs() {
// call the break method in EggController controller on each egg
}
}
EggController.java
public class EggController {
/***CONTROLS***/
@FXML private Label _eggID;
@FXML private TextField _eggColor;
public void doBreakEgg() {
// TODO: Break Egg
}
/****************************************************************
********** ACCESSORS ************
****************************************************************/
public String getEggID() {
return _eggID.getText();
}
public String setEggID(String id) {
return _eggID.setText(id);
}
public String getEggColor() {
return _eggColor.getText();
}
}
现在我如何从主控制器访问每个鸡蛋数据和方法?无需为每个鸡蛋提供ID并在MainController中引用它。
答案 0 :(得分:1)
加载FXMLLoader
时从EggView.fxml
获取控制器,并将它们放入列表中。 (顺便说一句,不要使用鼠标监听器来处理按钮操作。)
public class MainController implements Initializable {
/***CONTROLS***/
@FXML private VBox _eggsContainer;
@FXML private Button _btnAddEgg;
@FXML private Button _btnPrintEggs;
@FXML private Button _btnBreakEggs;
private final List<EggController> eggs = new ArrayList<>();
@Override
public void initialize(URL location, ResourceBundle resources) {
_btnAddEgg.setOnAction(e -> {
doAddEgg();
});
_btnPrintEggs.setOnAction(e -> {
doPrintAllEggs();
});
_btnBreakEggs.setOnAction(e -> {
doBreakAllEggs();
});
}
// Add an egg to _eggsContainer
private void doAddEgg() {
HBox eggControl = null;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("EggView.fxml"));
eggControl = loader.load();
EggController controller = loader.getController();
eggs.add(controller);
} catch (IOException e) {
e.printStackTrace();
}
_eggsContainer.getChildren().add(eggControl);
}
private void doPrintAllEggs() {
// prints ID and Color of each egg in _eggsContainer
for (EggController controller : eggs) {
System.out.println(controller.getEggId() + " : " + controller.getEggColor());
}
}
private void doBreakAllEggs() {
eggs.forEach(EggController::doBreakEgg);
}
}