0

Considering this example how do I get or set anything on the form from the Main code?

All we have is a simple Main function like

@Override
public void start(Stage stage) throws Exception {
  Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

  Scene scene = new Scene(root, 300, 275);

  stage.setTitle("FXML Welcome");
  stage.setScene(scene);
  stage.show();
}

A form defined in FXML.

And a controller class which is never instantiated explicitly.

As I don't have a link to the controller class instance in the Main code, how do I access anything on the form from outside the controller?

DunDev
  • 210
  • 2
  • 13
Ivan
  • 63,011
  • 101
  • 250
  • 382

1 Answers1

1

One thing you can do is have create a default constructor for the controller and have it store this into a private static variable. You can then create a static getter for that variable to retrieve the controller instance. You can then either expose the @FXML-annotated fields directly or have getter methods for them. This breaks though if you load multiple instances of the same controller, for obvious reasons.

I don't have much experience with JavaFX, though, so I can't say for sure whether this is a good/bad solution... I just know it works for simpler cases.

Edit: This answer has better solutions: Accessing FXML controller class

Basically:

FXMLLoader fxmlLoader = new FXMLLoader();
Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
FooController fooController = (FooController) fxmlLoader.getController();
awksp
  • 11,764
  • 4
  • 37
  • 44
  • Don't use static variables to expose data in the controller. Controller data is inherently non-static as it is specific to the controller instance. – James_D Apr 29 '14 at 17:37
  • Yeah, I realized... It works as long as you're careful to load that FXML file only once at most, and it's convenient-ish in that one case, but it definitely wouldn't work if you have multiple instances of the same controller. – awksp Apr 29 '14 at 17:39