FXML control always null when using Kotlin
<p>Using IntelliJ I created a JavaFX application and then added Kotlin and Maven as frameworks to it. It came with a sample.fxml file and a Controller.java and Main.java. I created a new class for the controller in Kotlin (MainWindowController.kt) and renamed the sample.fxml file to MainWindow.fxml. I updated the MainWindow.fxml to look like:</p>

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

<p>And in my MainWindowController.kt file I have:</p>

<pre><code>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}")
    }
}
</code></pre>

<p>Here's my Main.java:</p>

<pre><code>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);
    }
}
</code></pre>

<p>When I run the app the print line shows that the label is null but otherwise the window shows properly and I see the text from my label. The null is the problem I'm having. I haven't found much on using FXML with Kotlin and what I did find was a little out-dated and didn't appear to have an actual working solution.</p>

<p>Does anyone know why the label is null? I must be doing something wrong or misunderstanding something.</p>

<p>Edit: Here's what I have that now works thanks to the quick replies:</p>

<pre><code>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}")
    }
}
</code></pre>