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 from App");
Also, you can always declare variables in a Controller public and use them directly. While it's not advised for production code, it can simplify prototyping.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139