Using FXML file
In order to access a controller from FXML, you need to use the fx:id
attribute to give your controller a unique identifier. Then, you can use the fx:controller
attribute in the root element of your FXML file to specify the controller class. Here is an example:
<!-- Main.fxml -->
<BorderPane fx:controller="com.example.MainController"
xmlns:fx="http://javafx.com/fxml"
fx:id="root">
<center>
<TextField fx:id="textField" />
</center>
</BorderPane>
// MainController.java
public class MainController {
@FXML
private BorderPane root;
@FXML
private TextField textField;
// Initialize method that is called after the FXML is loaded
public void initialize() {
// Do something with root and textField
}
}
In the initialize
method of the controller, you can then access the root
and textField
nodes by using their fx:id
values.
This is because the FXML loader will automatically inject these values into the corresponding fields of the controller.
Using FXMLLoader
Alternatively, you can use the FXMLLoader
class to load the FXML file and access the controller directly. Here is an example of how you can do this:
// Main.java
public class Main extends Application {
public void start(Stage stage) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
Parent root = loader.load();
MainController controller = loader.getController();
// Do something with controller
}
}
In this example, the FXMLLoader
is used to load the FXML file and get a reference to the MainController
instance. This reference can then be used to access the controller and its methods and fields.