我有一个带有 main.fxml 的 FXML 应用程序,其中包含另外两个 fxml 文件。每个 fxml 文件都有自己的 Controller 类。
我的问题是,如何从特定 Controller 访问对象,尽管这些对象是在另一个 fxml 文件中定义的。
以下代码只是一个最小的示例。我认为将 ui 元素拆分到不同的 fxml 文件中是个好主意,因为它们变得越来越大。
我的主要 fxml:
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<fx:include fx:id="top" source="top.fxml"/>
<fx:include fx:id="bottom" source="bottom.fxml"/>
</VBox>
top.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="ControllerTop">
<children>
<Button fx:id="topbtn" onAction="#printOutput" text="OK" />
</children>
</VBox>
底部.fxml
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="ControllerBottom">
<children>
<Button fx:id="bottombtn" onAction="#printOutput" text="OK" />
</children>
</VBox>
对于top.fxml,我创建了这个 Controller 类:
public class ControllerTop {
@FXML public Button topbtn;
@FXML public Button bottombtn;
@FXML
public void printOutput() {
System.out.println("Hello from top button");
topbtn.setDisable(true); //OK!
bottombtn.setDisable(false); //Failed
}
}
当然bottombtn是在bottom.fxml中定义的并且有自己的 Controller 。问题是,此 ControllerTop 的 printOut() 的 Bottombtn 会导致 NullPointerException。因此,我需要帮助以一种良好且智能的方式访问对象。
谢谢
最佳答案
在主 Controller 中:
public class MainController {
/**
* var name has to be topController
*/
public TopController topController;
/**
* var name has to be bottomController
*/
public BottomController bottomController;
public void initialize(){
Button topbtn=topController.topbtn;
Button bottombtn=bottomController.bottombtn;
topbtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello from top button");
topbtn.setDisable(true); //OK!
bottombtn.setDisable(false); //Failed
}
});
}
}
底部.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="BottomController">
<children>
<Button fx:id="bottombtn" text="OK" />
</children>
</VBox>
top.fxml:
<VBox fx:id="vbox" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="TopController">
<children>
<Button fx:id="topbtn" text="OK" />
</children>
</VBox>
并在类 TopController 和 BottomController 中设置 @FXML public Button **btnName**;
底部 Controller :
public class BottomController {
public Button bottombtn;
}
顶级 Controller :
public class TopController {
public Button topbtn;
}
另一个选项是在 MainController
中使用 initialize
来设置 topController 中 bottombtn
的值
关于java - 访问不同 fxml 文件中的 ui 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733618/