[英]Java FXML GridPane.getRowIndex(source) returning null always when handling mouse event in Scene Builder
[英]FXML control always null when using Kotlin
使用IntelliJ我創建了一個JavaFX應用程序,然后將Kotlin和Maven作為框架添加到其中。 它附帶了一個sample.fxml文件以及一個Controller.java和Main.java。 我在Kotlin(MainWindowController.kt)中為控制器創建了一個新類,並將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構造函數一樣, 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}")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.