gpt4 book ai didi

java - 使用 Kotlin 时 FXML 控件始终为空

转载 作者:IT老高 更新时间:2023-10-28 13:41:09 25 4
gpt4 key购买 nike

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

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.GridPane?>
<GridPane fx:controller="reader.MainWindowController" xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx/8" alignment="center" hgap="10" vgap="10">
<Label fx:id="helloLabel" text="Hello"/>
</GridPane>

在我的 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}")
}
}

最佳答案

如前所述。检查是否设置了 fx:id。

也可以使用 lateinit 修饰符。

您的代码可能如下所示:

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {
@FXML
lateinit var helloLabel : Label
}

关于java - 使用 Kotlin 时 FXML 控件始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com