Reputation:
I'm new the JavaFX and having some issues.
Let's say I have two fxml files, with a corresponding controller class. Each of the fxml has a button on it, which should open the other screen and pass a parameter.
Could someone please provide an example of how this is done, google hasn't been of any help.
Upvotes: 3
Views: 8012
Reputation: 55
@FXML
public void handleAddPartAction(ActionEvent event) throws IOException {
Stage stage;
Parent root;
//get reference to the button's stage
stage=(Stage) partAddButton.getScene().getWindow();
//load up OTHER FXML document
root = FXMLLoader.load(getClass().getResource("AddPart.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
Upvotes: 1
Reputation: 341
By "screens" you mean JavaFX Stage instances, right? If so, it is rather simple:
The only somewhat unusual thing is the acquiring of the controller reference. You need to create an instance of FXMLoader. It does not work with the usually called static methods:
(Main Class of the app)
public class MyFXMLApp extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("MainForm.fxml"));
Parent root = (Parent) loader.load();
// as soon as the load() method has been invoked, the scene graph and the
// controller instance are availlable:
MainFormController controller = loader.getController();
controller.setText("Ready.");
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
// ...
(The controller)
public class MainFormController implements Initializable {
// some ui control:
@FXML
private Label label;
// JavaFX property for values that shall be accessible from outside:
private final StringProperty text = new SimpleStringProperty();
public String getText() {
return text.get();
}
public void setText(String value) {
text.set(value);
}
public StringProperty textProperty() {
return text;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println("MainFormController.initialize");
this.label.textProperty().bind(this.text);
}
// ...
The example uses JavaFX properties for holding the "parameter" in the controller - thus, the value and it's change are easily observable and the property may be bound to any other string property.
Upvotes: 1