I am using javafx along with fxml, so I use the controller for the real coding. I need to do a few operations on the stage, such as getting
The best approach is to create a new controller and pass the stage via the constructor (don't use fx:controller on FXML file), otherwise the stage will be null when initialize() is invoked (At that moment of time, when load() invokes initialize(), no stage is attached to the scene, hence the scene's stage is null).
public class AppEntryPoint extends Application
{
private FXMLLoader loader;
@Override
public void init() throws Exception
{
loader = new FXMLLoader(getClass().getResource("path-to-fxml-file"));
}
@Override
public void start(Stage initStage) throws Exception
{
MyController controller = new MyController(initStage);
loader.setController(controller);
Scene scene = loader.load();
initStage.setScene(scene);
initStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
public class MyController
{
private Stage stage;
@FXML private URL location;
@FXML private ResourceBundle resources;
public MyController(Stage stage)
{
this.stage = stage;
}
@FXML
private void initialize()
{
// You have access to the stage right here
}
}