How to apply minimal changes to the GUI in javaFX

179 views Asked by At

Is there a preferred way to apply (small) changes to a GUI in javaFX? I prefer using FXML instead of doing it programmatically.

For example: The application starts up with a background and some buttons in a VBox (they are arranged like its defined in a FXML file).

Let's assume that an user presses a button (e.g. in a game the button is named "multiplayer") so the GUI has to change to display the next step.

In this example I like to achieve that the button is named something else, another button to be replaced with a text field and maybe some other small changes will be applied. But most of the GUI will stay the same e.g. the background, the VBox itself and some buttons.

Should I apply these changes programmatically using something like vbox.getChildren().remove(button); and vbox.getChildren().add(textField);? But why use FXML then? I could do the whole GUI programmatically instead of only loading the starting fxml scene and then apply changes programmatically.

Or should I load a new scene from a different FXML file where these changes are made inside the FXML file. But then I notice that my application needs a long time to load the new FXML file via FXMLLoader and displays a white screen for a short time.

Or should I split my FXML file into different layers so I can e.g. only exchange the VBox with another VBox instead of replacing the whole GUI? But how should I structure my GUI then, and can I still use SceneBuilder?

Probably all my ways are not the preferred ones. So how can I achieve my aim in a good way?

If you want to take a look at my current code, I posted it in this thread earlier.

1

There are 1 answers

0
user7291698 On

Instead of defining a Button or a TextField in the fxml, define a container there, for example a Pane. Then change what has to be inside this Pane in your controller:

@FXML 
private Pane flexiblePane;

private Button myButton = new Button();
private TextField myTextField = new TextField();


private void displayFlexiblePaneAsButton(boolean flag) {
    if (flag) {
        flexiblePane.getChildren().clear();
        flexiblePane.getChildren().add(myButton);
    }
    else {
        flexiblePane.getChildren().clear();
        flexiblePane.getChildren().add(myTextField);
    }
}