Working with Controllers
A question that is often asked is how to transfer data between an FXML Controller and other parts of the application. Let's look into the available options.
Enhancing Controllers
FXML Controllers are not set in stone; you can add methods to them and use them to transfer information.
Consider the following example for the FirstDocument.fxml
we used earlier in this chapter:
public class SmartController implements Initializable { public void setText(String newText) { textField.setText(newText); } @FXML private Button button; @FXML private TextField textField; @Override public void initialize(URL url, ResourceBundle rb) { button.setText("hello"); } }
Now, we can work with the FXML variables from other classes, as in the following example, from Application
:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FirstDocument.fxml")); HBox root = loader.load(); loader.<SmartController>getController().setText...