Вопрос

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?

Это было полезно?

Решение

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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top