0

I have a TextField and a button in FXMLController and a label in SecondFXMLController

Now I want to get Value of TextField in SecondFXMLController

Note: Two fxml files will be loaded in Same stage

FXMLController:

public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    @FXML
    private Button button;
    @FXML
    private TextField firstField;
    @FXML
    private AnchorPane first;

    private int a;

    @FXML
    private void handleButtonAction(ActionEvent event) throws IOException {
        AnchorPane pane = FXMLLoader.load(getClass().getResource("SecondFXML.fxml"));
        first.getChildren().setAll(pane);   
    }

    public String setTo() {
        System.out.println("In setTo function");
        System.out.println(firstField.getText());
        return firstField.getText();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    } 
}

SecondFXMLController:

public class SecondFXMLController implements Initializable 
{

    @FXML
    private Label secondField;
    private String f;
    private AnchorPane pane;
    private FXMLDocumentController con;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO

        FXMLLoader fxml = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));

        try {
            pane  = fxml.load();
            con = fxml.getController();
            f = con.setTo(); 
        } catch (IOException ex) {
           Logger.getLogger(SecondFXMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(f);
        secondField.setText(f);
    }    
}

Now problem is that i'am not able to fetch the value of textField in setTo() function so its returning null. NOTE: Both FXML files should be loaded in the Same Stage

Can Any one please give the Solution

ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176

1 Answers1

0

Instead of returning a String from the method, I would suggest to return a StringProperty. Later you can bind this String Property to the textProperty of the Label.

public class FXMLDocumentController implements Initializable {

    ...
    @FXML
    private TextField firstField;
    ...

    public StringProperty firstFieldTextProperty() {
        return firstField.textProperty();
    }
    ...
}

In SecondFXMLController, just bind the secondLabel's textProperty to the method.

public class SecondFXMLController implements Initializable {

    @FXML
    private Label secondField;
    ...

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ...
        FXMLLoader fxml = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
        pane  = fxml.load();
        con = fxml.getController();
        secondField.textProperty.bind(con.firstFieldTextProperty());
        ...
    }    
}
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176