控制器在javafx helloworld中返回null

Dan*_*son 1 javafx-2 fxml

所以我当然直接创建一个简单的例子.

public class Main extends Application {

URL bla = getClass().getResource("/sample.fxml");

@Override
public void start(Stage primaryStage) throws Exception{
    //If you get weird errors: http://zenjava.com/javafx/maven/fix-classpath.html
        //but not actually my issue. Example displays fine in intellij.

    try {

        FXMLLoader loader = new FXMLLoader(bla);
        Parent root = loader.load(bla);

        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();

        Controller controller = loader.<Controller>getController() ;
        assert(controller != null);
        controller.getLabel().setText("Kaboom!");
    } catch (Exception e) {
        // Exception gets thrown if the fxml file could not be loaded
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了https://forums.oracle.com/thread/2317621 ,我知道顶部的anchorpane需要指向fxml中的Controller.

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"      minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0" xmlns:fx="http://javafx.com/fxml" fx:controller="mypackage.Controller">
  <children>
Run Code Online (Sandbox Code Playgroud)

它显示正常,但断言捕获因为没有控制器!
另外,initialize()没有实际运行,这意味着将创建以下控制器!

public class Controller {

@FXML
private Label label ;

public Label getLabel()
{
    return label ;
}

@FXML
public void initialize()
{
    System.out.println("Swear a lot!");
    System.out.println(label);
}
}
Run Code Online (Sandbox Code Playgroud)

如果您正在观看此事,请向外汇开发商提供一份说明:

如果你要在指向类的xml文件中使用弱耦合字符串,我真的希望.load()在找不到它正在寻找的内容时抛出一个有意义的运行时异常.没有理由永远返回null ...理想情况下从GWT小部件团队中获取一个页面,并且在程序实际开始之前让预编译器失败,或者为流行的IDE提供最好的插件.

此外,你真的应该尽快为JavaFX启动和运行JavaFX的源代码(把它放在maven中),因此它可以自动下载,我可以自己解决问题.太难.

我确信有一些简单的我做错了,但工具应该让我免于此.

Ulu*_*Biy 6

能够像这样得到控制器类

Controller controller = loader.<Controller>getController();
Run Code Online (Sandbox Code Playgroud)

你需要调用实例化的FXMLLoader的加载方法,即
代替

Parent root = loader.load(bla);
Run Code Online (Sandbox Code Playgroud)

这里load()是静态的,调用

Parent root = (Parent) loader.load(bla.openStream());
Run Code Online (Sandbox Code Playgroud)

但我同意它应该有详细记录.