Pergunta

I'm looking for a way of registering to the FXML component injection on the controller. so I would have method like so

void afterComponenetInjection();

That will be fired once FXML componenets are injected.

Foi útil?

Solução

There is no such direct mechanism. However, all injection is guaranteed to be completed before the controller's initialize() method is called, so you could put such functionality in that method.

Alternatively, if you want this to be external to the controller itself, retrieve the controller from the FXMLLoader; once the load() method returns, injection will have been completed (and the initialize() method will be complete), so you can invoke any functionality you need after calling load().

And I suppose a third option: Define a BooleanProperty in the controller, and set it to true at the beginning of the initialize() method. Then register a listener with that property: again, since injection is complete before initialize() is called, your listener will be invoked when injection is complete. Something like:

public class MyController {
   @FXML
   private Node node1 ;
   @FXML
   private Node node2 ;

   private final ReadOnlyBooleanWrapper injected = new ReadOnlyBooleanWrapper(this, "injected", false);

   public boolean isInjected() {
      return injected.get();
   }

   public ReadOnlyBooleanProperty injectedProperty() {
      return injected.getReadOnlyProperty();
   }

   public void initialize() { 
      injected.set(true);
      // other initialization...
   }
}

// elsewhere...
FXMLLoader loader = new FXMLLoader(getClass().getResource(...));
MyController controller = new MyController();
loader.setController(controller);
controller.injectedProperty().addListener( /* will be invoked after injection....*/ );
Parent root = (Parent) loader.load();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top