You give the controller access to the UI elements defined in the FXML by injection. Specifically, in the FXML, give the UI element a fx:id
attribute:
<Button fx:id="someButton" mnemonicParsing="false" prefHeight="25.0" prefWidth="61.0" text="Browse" />
Now in your controller, define an @FXML
-annotated field with a name that matches the fx:id
attribute value:
public class Controller {
@FXML
private Button someButton ;
}
Now you can configure the button with whatever logic you need:
public class Controller {
@FXML
private Button someButton ;
public void initialize() {
String foo = "foo" ;
someButton.setText(foo);
}
}
To answer the "how does all this fit together" part of your question, consider the FXML and controller as a pair. The FXML defines the layout, while the controller defines the logic (handling user input, etc). The controller has access to the elements of the UI defined in the FXML file using the mechanism described above.
When an FXMLLoader
loads the FXML file, in the default setup, the FXMLLoader
creates an instance of your controller class, injects the @FXML
-annotated fields into the controller instance, and calls the controller instance's initialize()
method.
The Application
subclass exists just as the starting point for your application. It will typically just load an FXML file, put the root of the FXML in a Scene
and display the Scene
in a primary stage. If you have a more complex application, you might also start up some services and background threads here.