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("Text ...

Get Mastering JavaFX 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.