Let's say I have three files:
- Controller.java
- Creator.java
- Scene.fxml
Scene.fxml's controller is set to Controller.java. Controller.java calls a method from Creator.java which creates a new scene using FXMLLoader.load( ) method, then passes this scene to newly created stage and returns this stage. Controller.java calls .show() method on that returned stage. Everything is great so far, the window did pop up, but the issue is that I can not access any node from Scene.fxml in Controller.java. I naturally have "fx:id" stuff in Scene.fxml and I've also created all those nodes in Controller.java with the exact name and @FXML annotation. Anyway, they are all set to NULL.
I assume that the issue might be connected with FXMLLoader.load() method being called from s class that is not the class controller. So the question is: am I right? i If I am, is there any way to actually make it work the way I want?
If the explanation is not good enough I will create a minimal reproducible example.
EDIT:
Controller.java:
package Issue;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class Controller extends Application {
@FXML
private Label label;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
stage = Creator.createStage(stage);
stage.show();
System.out.println("Is label null?");
if(label == null){
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
Creator.java:
package Issue;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Creator {
public static Stage createStage(Stage stage) {
Parent root = null;
String pathToProject = System.getProperty("user.dir");
Path path = Paths.get(pathToProject, "src", "main", "java", "Issue", "Scene.fxml");
try{
URL url = new URL("file", "", path.toString());
root = FXMLLoader.load(url);
} catch (IOException | NullPointerException e) {
System.out.println("wrong url to fxml");
}
stage.setScene(new Scene(root, 400, 400));
return stage;
}
}
Scene.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="Issue.Controller"
prefHeight="400.0" prefWidth="600.0">
<center>
<Label fx:id="label" text="hey stackoverflow"/>
</center>
</BorderPane>
module-info.java:
module Main {
requires javafx.controls;
requires javafx.fxml;
opens Issue to javafx.fxml;
exports Issue;
}
I've created standard Maven projects and created "Issue" package with those files in src/main/java path. module-info.java is in src/main/java.