使用JavaFX作为应用程序,我有一个Main.fxml文件,里面有一些fxml子文件。
using JavaFX for an application and I have a Main.fxml file with some fxml child files inside it.
我想访问Main的MainController类。来自子控制器的fxml。
I would like to access to MainController class of Main.fxml from the child Controllers.
我将尝试用一个例子更好地解释:
I'll try to explain better with an example:
MainFxml:
<HBox fx:controller="MainController.java"> <fx:include source="child.fxml"/> </HBox>MainController:
MainController:
public class MainController implements Initializable { private String string; public void setString (String string) { this.string = string; }ChildFxml:
ChildFxml:
<HBox fx:id="child" fx:controller="ChildController.java"> <Button text="hello" onAction="#selectButton"></Button> </HBox>ChildController:
ChildController:
public class ChildController implements Initializable { @FXML HBox child; @FXML Button button; @FXML public void selectButton (ActionEvent event) { // here call MainController.setString("hello"); }我试过在StackOverflow上找到此解决方案但我需要获取已加载的Main.fxml的Controller引用。 是否有任何方法可以从特定窗格启动Controller? 类似于:
I tried this solution found on StackOverflow but I need to get the Controller reference of the Main.fxml that has been already loaded. Is there any method to get the Controller starting from a specific Pane? Something like:
// child.getParent().getController();推荐答案
如果您指定 fx :id 到< fx:include> 标记, FXMLLoader 尝试注入包含fxml的控制器到名为< fx:id> Controller 的字段。您可以在初始化方法中将 MainController 引用传递给子控制器:
If you assign a fx:id to the <fx:include> tag, FXMLLoader tries to inject the the controller of the included fxml to a field named <fx:id>Controller. You can pass the MainController reference to the child controllers in the initialize method:
<HBox fx:controller="MainController.java"> <fx:include fx:id="child" source="child.fxml"/> </HBox>MainController
MainController
@FXML private ChildController childController; @Override public void initialize(URL url, ResourceBundle rb) { childController.setParentController(this); }ChildController
ChildController
private MainController parentController; public void setParentController(MainController parentController) { this.parentController = parentController; } @FXML private void selectButton (ActionEvent event) { this.parentController.setString("hello"); }
然而会更好练习保持 ChildController 独立于父级。这可以通过在 ChildController 中提供 StringProperty 来完成,该值设置为父应显示的值。
It would however be better practice to keep the ChildController independent from the parent. This could be done by providing a StringProperty in the ChildController that gets set to the value the parent should display.
private final StringProperty value = new SimpleStringProperty(); public StringProperty valueProperty() { return value; } @FXML private void selectButton (ActionEvent event) { value.set("hello"); }ParentController
ParentController
@Override public void initialize(URL url, ResourceBundle rb) { childController.valueProperty().addListener((observable, oldValue, newValue) -> setString(newValue)); }更多推荐
JavaFX从FXML子访问父控制器类
发布评论