简体   繁体   中英

How to initialize member variables of a custom javafx controller?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM