0

For some reason I'm not able to load nodes defined in an FXML file into my instance variables. I have made these two test files:

Test.java:

public class Test extends Application {
    @FXML private TextArea ta;
    @FXML private Label l;

    public void start(Stage primaryStage) {
        Scene scene = null;
        try {scene = new Scene((BorderPane)FXMLLoader.load(Test.class.getResource("ChatServer.fxml")));}
        catch (IOException e) {}

        primaryStage.setScene(scene);
        primaryStage.setTitle("Chat Server");
        primaryStage.show();
        System.out.println(ta);
        System.out.println(l);
    }
}

FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Test">
   <top>
      <Label fx:id="l" text="text" BorderPane.alignment="CENTER">
         <BorderPane.margin>
            <Insets bottom="10.0" top="10.0" />
         </BorderPane.margin>
         <font>
            <Font size="13.0" />
         </font>
      </Label>
   </top>
   <center>
      <TextArea fx:id="ta" editable="false" focusTraversable="false" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
   </center>
</BorderPane>

Both the TextArea and the Label are printed out as null when they should have been injected with the nodes defined in the FXML file, does anyone know what's wrong here? Both the controller class and the fields are found and recognized when I edit the FXML file in Scene Builder, so there shouldn't be any problems.

Just some guy
  • 1,909
  • 4
  • 21
  • 32

1 Answers1

1

FXMLLoader.load creates a new instance of your Test class. So this will not be the same as your current class.

User the setControllerFactory method of the FXMLLoader class to change this behaviour.

mh-dev
  • 5,264
  • 4
  • 25
  • 23