4

In the Spring framework, i can use the configuration files to load member variables of a class. Is there a way to do this in javafx with a custom controller or a custom object?

j will
  • 3,747
  • 11
  • 41
  • 64

1 Answers1

9

The @FXML annotation enables the JavaFX objects whose names you defined (fx:id) to have their references reflectively injected into nonpublic fields in the controller object as the scene graph is loaded from the fxml markup.

You can accomplish something very similar to what you are requesting by defining the values that you want set as class variables in your controller object's class, and then setting the appropriate object properties programmatically (rather than in markup) in the initialize() method of your controller object.

The initialize() method is called (if it is present) after the loading of the scene graph is complete (so all the GUI objects will have been instantiated) but before control has returned to your application's invoking code.

Edit

You can use @FXML only in Controller which is specifically set in fxml file and only for fields of that class.

This is required because these fields would be initialized automatically during creation of that class' object.

 public class MyController implements Initializable{

      @FXML
      Button startButton;

      void initialize(java.net.URL location, java.util.ResourceBundle resources) {
           startButton.addActionLisetner(...);
      }

 }

Detailed tutorial is here

Russell Shingleton
  • 3,176
  • 1
  • 21
  • 29
Imran
  • 5,376
  • 2
  • 26
  • 45
  • do you have an example? – j will Dec 02 '13 at 18:57
  • Thank you for the answer, I posted another question that i think will better suit the problem i initially had. http://stackoverflow.com/questions/20389567/how-to-initialize-javafx-controllers-with-the-same-model-object – j will Dec 05 '13 at 01:18
  • [`Initializable` is deprecated](https://docs.oracle.com/javafx/2/api/javafx/fxml/Initializable.html). – m0skit0 Dec 01 '15 at 18:17