从正在运行的 javafx 应用程序打开新的 javafx 窗口时,我无法将 fxml 变量绑定(bind)到 Controller 类中的局部变量。
请注意,对于正在运行的应用程序,我可以毫无问题地绑定(bind)到类似名称的变量,从而在运行时在正在运行的应用程序中填充组合框。欢迎任何解决方案。
调用新类(ServerConfigChooser)的代码
FXMLLoader loader = new FXMLLoader(getClass().getResource("ServerConfigChooser.fxml"));
try{
Stage stage = new Stage();
stage.setScene(new Scene( (Parent) loader.load()));
stage.show();
} catch (IOException ex)...
在运行的应用程序中工作的绑定(bind)示例(在运行时执行的代码)
@FXML
public ComboBox cb_01_fxid;
private void initComboBox(){
cb_01_fxid.getItems().add(0, "yes");
cb_01_fxid.getItems().add(0, "no");
}
Controller 类中的 fxid“cb_01_fxid”与 .fxml 文件中 ComboBox 对象的 fxid 相同。这样绑定(bind)就没有问题了。以下是新窗口的 Controller 类 (ServerConfigChooser) 的代码。
1 @FXML
2 public ComboBox cb_02_fxid;
3
4 public void initComboBoxNewWindow(){
5 cb_02_fxid.addItems(0, "test item 1");
6 }
以及主应用程序中的相关 fxml 行
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="728.9999000000025" prefWidth="735.0000999999975" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="model.Sample">
和新窗口
<fx:root type="javafx.scene.layout.AnchorPane" id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="283.0" prefWidth="445.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="model.ServerConfigChooser">
<ComboBox id="cb_02_fxid" layoutX="256.0" layoutY="84.0" onAction="#scc_cb_action">
程序在第 5 行抛出空指针异常(添加行号以供引用)。有谁知道为什么第二个 Controller 没有绑定(bind)到第二个 fxml 对象?提前致谢
最佳答案
您的 ComboBox fxml 部分应设置 fx:id
属性:
<ComboBox fx:id="cb_02"
此 ID 应该与 Controller 类中的变量具有完全相同的名称。
详情请参阅教程:http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm
关于JavaFX Controller 类变量未绑定(bind)到其 FXML 对应项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21266694/