Reputation: 21
In my javafx Application we have two FXML files first.fxml and second.fxml, same firstController.java and secondController.java now the main problem is first.fxml contain TextField name and on Button when user will click on that button second.fxml display in second.fxml I have one ComboBox and one Button when user click second.fxml button I want to set that combobox value to first.fxml name TextField.
I am finding solution on Google from last three days but didn't get proper solution. In Java swing I was doing this using static public field that allowed me to access JFrame from another JFrame.
Eagerly waiting for helpful reply.
Upvotes: 2
Views: 9887
Reputation: 209330
Expose a StringProperty
from your SecondController
. When the button is pressed, set its value:
public class SecondController {
private final StringProperty selectedValue = new SimpleStringProperty(this, "selectedValue", "");
public final StringProperty selectedValueProperty() {
return selectedValue ;
}
public final void setSelectedValue(String value) {
selectedValue.set(value);
}
public final String getSelectedValue() {
return selectedValue.get();
}
@FXML
private final ComboBox<String> comboBox ;
@FXML
private void handleButtonPress() {
selectedValue.set(comboBox.getValue());
}
}
In your FirstController
, provide a method for setting the text:
public class FirstController {
@FXML
private TextField textField ;
public void setText(String text) {
textField.setText(text);
}
}
Now when you load the FXML files, just observe the property in the SecondController
and call the method in FirstController
when it changes:
FXMLLoader firstLoader = new FXMLLoader(getClass().getResource("first.fxml"));
Parent first = firstLoader.load();
FirstController firstController = firstLoader.getController();
FXMLLoader secondLoader = new FXMLLoader(getClass().getResource("second.fxml"));
Parent second = secondLoader.load();
SecondController secondController = secondLoader.getController();
secondController.selectedValueProperty().addListener((obs, oldValue, newValue) ->
firstController.setText(newValue));
Upvotes: 2