I have pretty simple application (i just want to understand controller switching mechanism). First window shows label and button. When you click the button, another window with button will show. Now when you click this second button, Label in first window should change. I have read some posts here, also tried this one Java FX change Label text in a previous stage scene, however, with no success. If you could explain it to me on this simple example, maybe i will be able to better understand controllers logic. Here is my code, thank for any help:
PrimaryController with label to be changed and the button, which opens new window
public class PrimaryController implements Initializable {
@FXML
private Label label;
@FXML
private Button btnButton;
@Override
public void initialize(URL url, ResourceBundle rb) {
btnButton.setOnAction((event) -> {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("secondaryFXML.fxml"));
Parent root = loader.load();
loader.<SecondaryController>getController().setPrimaryController(this);
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
Logger.getLogger(PrimaryController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
public void setLabelText(String string){
label.setText(string);
}
}
Secondary Controller with change label button
public class SecondaryController implements Initializable {
@FXML
private Button btnChangeLabel;
private PrimaryController primary;
@Override
public void initialize(URL url, ResourceBundle rb) {
btnChangeLabel.setOnAction((event) -> {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("primaryFXML.fxml"));
loader.load();
PrimaryController primaryCtrl = loader.<PrimaryController>getController();
primaryCtrl.setLabelText("eres");
} catch (IOException ex) {
Logger.getLogger(SecondaryController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
public void setPrimaryController(PrimaryController primary){
this.primary = primary;
}
}