How to call functions on the stage in JavaFX's controller file

Pratik Anand picture Pratik Anand · May 19, 2013 · Viewed 25.8k times · Source

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 its x- or y-axis position. I have tried stage.getX() & stage.getY, but they don't work(the stage name is high-lited as the error). How do I use such functions in my controller? I tried doing this in my main file:

 public int locationX = stage.getX();

and

public double locationX = stage.getX();

But it doesn't work, instead makes the whole program one big error.
So how do I get to do such functions in my controller file? Do I need to import something or do something like above in another way?

error: cannot find symbol
    locationX = stage.getX();
symbol:   variable stage
location: class FXMLController


I know that the "stage" is missing. But how to get the "stage" in my controller?

Answer

tarrsalah picture tarrsalah · May 20, 2013

From your root Pane in the fxml file :

@FXML
Parent root

You can get the stage from it by:

Stage stage = (Stage) root.getScene().getWindow()

You have a reference to your stage, you can do what you want.