1

I have gone through this similar question but it use Singleton Class. Also other similar question which I found are mainly nested controllers. So I am raising this simple question hoping to get an answer for binding text property of two TextFields which are in different FXML.

I have two textfields in two different fxmls and these are their controller classes:

TextField1Controller.java

public class TextField1Controller implements Initializable{

@FXML
TextField txt1FxId;

@Override
public void initialize(URL location, ResourceBundle resources) {


}
}

TextField2Controller.java

public class TextField2Controller implements Initializable{

@FXML
TextField txt2FxId;

@Override
public void initialize(URL location, ResourceBundle resources) {

}
}

MainApp.java

public class MainApp extends Application{

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage1) throws Exception {      
    AnchorPane pane1  = FXMLLoader.load(this.getClass().getResource("TextField1.fxml"));
    AnchorPane pane2  = FXMLLoader.load(this.getClass().getResource("TextField2.fxml"));        
    Stage stage2 = new Stage(); 
    stage1.setScene(new Scene(pane1));
    stage2.setScene(new Scene(pane2));  
    stage1.show();
    stage2.show();  

}

}

How can I bind the text property of those textfields in my MainApp.java so that typing on one textfield prints on the other text field and vice versa?

Community
  • 1
  • 1
Angom
  • 721
  • 1
  • 11
  • 27

1 Answers1

4

The approach would be:

  • use an instantiated FXML loader and call its non-static methods,
  • put accessors for the textfields in the related controllers and get them,
  • bind the textfields bi-directionally.

Implementation:

Put the getter

public TextField getTxt1FxId() {
    return txt1FxId;
}

into TextField1Controller class and getTxt2FxId() into second one.
The main app,

@Override
public void start(Stage stage1) throws Exception {
    FXMLLoader loader = new FXMLLoader();
    Parent pane1 = (Parent) loader.load(getClass().getResource("TextField1.fxml").openStream());
    TextField1Controller controller1 = loader.getController();

    loader = new FXMLLoader();
    Parent pane2 = (Parent) loader.load(getClass().getResource("TextField2.fxml").openStream());
    TextField2Controller controller2 = loader.getController();

    controller1.getTxt1FxId().textProperty().bindBidirectional(
                    controller2.getTxt2FxId().textProperty());

    Stage stage2 = new Stage(); 
    stage1.setScene(new Scene(pane1));
    stage2.setScene(new Scene(pane2));  
    stage1.show();
    stage2.show();  

}
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153