我有一个BorderPane(与MainController相关联),BorderPane的FXML使用<fx:include>
将Label(带有控制器StatusBarController)包含在BorderPane的底部区域。不幸的是,StatusBarController没有注入MainController类实例,我无法理解为什么。
main.fxml:包含状态栏的BorderPane
<fx:root type="javafx.scene.layout.BorderPane" fx:id="borderPane" xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.controllers.MainController">
<bottom>
<fx:include source="statusbar.fxml" />
</bottom>
</fx:root>
statusbar.fxml:标签及其关联的控制器
<Label fx:id="statusbar" text="A label simulating a status bar" xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.controllers.StatusBarController" />
带有StatusBarController字段的MainController:
public class MainController
{
@FXML
private StatusBarController statusbarController; // PROBLEM HERE: I would expect the StatusBarController to be injected but this does not happen!
// Implementing Initializable Interface no longer required on JavaFX 2.2 according to
// http://docs.oracle.com/javafx/2/fxml_get_started/whats_new2.htm
// (I also tested this, the initialize() method is being called)
@SuppressWarnings("unused") // only called by the FXMLLoader
@FXML // This method is called by the FXMLLoader when initialization is complete
private void initialize() {
// initialize your logic here: all @FXML variables will have been injected
assert borderPane != null : "fx:id=\"borderPane\" was not injected: check your FXML file 'main.fxml'.";
System.out.println("MainController initialize()");
//statusbarController.setStatusText("Hello from MainController"); // PROBLEM HERE: this fails because statusbarController is not injected as expected
}
}
应用程序的开始:
public void start(Stage primaryStage)
{
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("/resources/main.fxml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
primaryStage.setTitle("Demo");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
我的样本的完整源代码可在http://codestefan.googlecode.com/svn/trunk/SubcontrollerAccess/
获得所以问题是:为什么StatusBarController没有注入到MainController的statusbarController变量中?
感谢任何提示!
答案 0 :(得分:18)
要使用@FXML
代码,您必须提供fx:id
。
更新main.fxml
:
<bottom>
<fx:include fx:id="statusbar" source="statusbar.fxml" />
</bottom>
之后,您可以使用MainController.java
中的下一个常量:
@FXML
Label statusbar; // node itself
@FXML
private StatusBarController statusbarController; // controller
请注意,statusbarController
不是部分小写的类名,而是fx:id
+ Controller
字。
答案 1 :(得分:0)
netbeans 8.0中似乎也存在嵌套fxmls的错误。不能指望netbeans为你创建嵌套的fxml的控制器对象,它必须手动插入你的MainController。每次控制器在netbeans中更新它都会被消灭,所以它可能有点乏味。对于这个插入
的例子@FXML private StatusBarController statusbarController;
在这种情况下,手动进入主控制器,然后它正常工作。对于组织大型fxmls /控制器非常有用。