使用Kotlin时,FXML控件始终为空

使用IntelliJ我创建了一个JavaFX应用程序,然后将Kotlin和Maven作为框架添加到它。 它带有一个sample.fxml文件和一个Controller.java和Main.java。 我在Kotlin(MainWindowController.kt)中为控制器创建了一个新类,并将sample.fxml文件重命名为MainWindow.fxml。 我更新了MainWindow.fxml,如下所示:

    

在我的MainWindowController.kt文件中,我有:

 package reader import javafx.fxml.FXML import javafx.scene.control.Label class MainWindowController { @FXML var helloLabel: Label? = null init { println("Label is null? ${helloLabel == null}") } } 

这是我的Main.java:

 import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("MainWindow.fxml")); primaryStage.setTitle("My App"); primaryStage.setScene(new Scene(root, 1000, 600)); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

当我运行应用程序时,打印行显示标签为空,否则窗口显示正常,我看到我的标签文本。 null是我遇到的问题。 我还没有发现在Kotlin上使用FXML,我发现有点过时,似乎没有一个实际的工作解决方案。

有谁知道为什么标签为空? 我一定是做错了什么或误解了什么。

编辑:这是我有,现在的作品感谢快速回复:

 package reader import javafx.fxml.FXML import javafx.scene.control.Label class MainWindowController { @FXML var helloLabel: Label? = null fun initialize() { println("Label is null? ${helloLabel == null}") } } 

就像使用Java构造函数一样, fx:id字段在调用init (或者在Java构造函数)之前,不会被填充。 一个常见的解决方案是实现Initializable接口(或者只是定义一个initialize()方法),并在方法内部做如下附加的设置:

 import javafx.fxml.FXML import javafx.scene.control.Label class MainWindowController : Initializable { @FXML var helloLabel: Label? = null override fun initialize(location: URL?, resources: ResourceBundle?) { println("Label is null? ${helloLabel == null}") } } 

正如之前所提。 检查是否设置了fx:id。

也可以使用lateinit修饰符。

您的代码可能如下所示:

 import javafx.fxml.FXML import javafx.scene.control.Label class MainWindowController { @FXML lateinit var helloLabel : Label } 
Interesting Posts