1

Is this approach lame to do so?

I've tried many approaches e.g.

  1. How can I exchange data between forms
  2. JavaFX pass values from child to parent
  3. JavaFX 2.2 -fx:include - how to access parent controller from child controller

but this seems to be pretty direct and understandable.

public class ParentController {

    private Settings settings;

    public void setSettings(Settings settings) {
            this.settings = settings;
            System.out.println(this.settings.toString());
    }

    @FXML
    private Button open;

    @FXML
    private void pass() throws IOException {
            Stage st = new Stage();
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Child.fxml"));
            Region root = (Region) loader.load();

            Scene scene = new Scene(root);
            st.setScene(scene);

            ChildController controller = loader.<ChildController>getController();
            controller.initialize(this);
            st.show();
    }
}
public class ChildController {

    @FXML
    private TextField number; // some settings

    @FXML
    private Button ok;

    private ParentController parentController ;

    @FXML
    public void pass() {
            Stage stage = (Stage) ok.getScene().getWindow();
            parentController.setSettings(setSettings());
            stage.close();
    }

    private Settings setSettings(){
            return new Settings(Integer.valueOf(this.number.getText()));
    }

    public void initialize(ParentController parentController) {
            this.parentController = parentController;
    }
}

In such the way I'm getting settings object generated in Child controller and pass this object to the parent controller.

This works...

Is this approach appropriate? If not, what pitfall is may imply?

Community
  • 1
  • 1
Andreas Gelever
  • 1,736
  • 3
  • 19
  • 25

2 Answers2

0

The question is probably too opinion-based for this forum. The trade-off for the simplicity you gain (compared to, say, JavaFX pass values from child to parent) is that you have tightly-coupled the child to the parent: in other words you can't use the child view/controller in any context where you don't have that specific parent. In the linked approach, the child view/controller have no dependency on the parent. Whether or not this is desirable/beneficial/worth the added complexity will depend on your exact use case.

Community
  • 1
  • 1
James_D
  • 201,275
  • 16
  • 291
  • 322
0

I thought it was appropriate. for me it was just a coding style.

but in my opinion , change your settings variable to public static, stored in the Main class and initialized in the Main class, to be accessible at all controllers or other classes. thats my style :D

public static settings Settings;

Main.settings.( Something)

Happy coding..

ijoh
  • 1
  • 2