Rafael Coelho
Rafael Coelho

Reputation: 166

Which is the best way to pass information between windows in JavaFX?

I am using the code below to pass the information, but i would like to know other ways. In the event handler method handleSubmitButtonAction of FXMLDocumentController, i create another window loading MainFXML file. After that, i get hold of its controller and send my information to Main Window. Is there a better way to do that?

public class FXMLDocumentController implements Initializable {

    @FXML
    private TextField user;

    @FXML
    public void handleSubmitButtonAction(ActionEvent event) throws IOException {
        Alert dialogo = new Alert(Alert.AlertType.INFORMATION, "User: " + user.getText() + " logged in.");
        dialogo.showAndWait();
        Stage stage2 = (Stage) user.getScene().getWindow();
        stage2.close();

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MainFXML.fxml"));        
        Parent root = (Parent) fxmlLoader.load();
        MainFXMLController controller = fxmlLoader.<MainFXMLController>getController();        

        Scene scene = new Scene(root);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        controller.setUser(user.getText());        
    }

Upvotes: 0

Views: 318

Answers (1)

M. le Rutte
M. le Rutte

Reputation: 3563

Trying to give a short answer.

What I do is that I create an "application model" of the controller classes. The root of the application model is of course the controller of the Application class. The application model does not leak the GUI elements, but tells the main program about being closable, having changed etc.

public abstract class Part {
       public final ObservableMap<String, ActionHandler> getActionHandlers() {...}    
       public final ObservableBooleanValue closableProperty() {...}
       public final ReadOnlyBooleanProperty disabledProperty() {...}
       ....
}

public abstract class ViewPart extends Part {
       public final StringProperty titleProperty() { ... }
       public final ReadOnlyObjectProperty<Image> iconProperty() { ... }
       ....
}

public abstract class Editor extends Part {
        public final ObservableBooleanValue dirtyProperty() { .... }
}

Like in Eclipse these parts can have their own window, but they not necessarily have, they can also be embedded in another window. This modeling is based loosely on Eclipse's structure.

Upvotes: 1

Related Questions