Black Glix Black Glix - 1 month ago 12
Java Question

JavaFX Same textarea with different Pane's

I have a project with maven, javafx and fxml. I have one main BorderPane,

welcome.fxml
, and Pane,
ready.fxml
.

My start method is;

@Override
public void start(Stage primaryStage) throws Exception {

try {
Pane root = (Pane) FXMLLoader.load(getClass().getResource("welcome.fxml"));
Scene scene = new Scene(root, 640, 480);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
makeAlert(e, false);
}
}


Now, I have a button in my
welcome.fxml
, and I want to change my BorderPane's center with
ready.fxml
. Here is my button handler;

@FXML
private void buttonHandler() throws IOException, InterruptedException {


stage = (Stage) myButton.getScene().getWindow();
Pane sub = (Pane) FXMLLoader.load(getClass().getResource("../ready.fxml"));
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("../welcome.fxml"));
root.setCenter(sub);

//Scene scene = new Scene(root, 640, 480);
//stage.getScene().setRoot(root);
}


UPDATE: Here is my mistake,as @James_D noticed, I load
welcome.fxml
again in my controller and so, my whole Scene changes insted of only center.

The correct way should be;

stage = (Stage) brokerConnect.getScene().getWindow();
Pane center = (Pane) FXMLLoader.load(getClass().getResource("../ready.fxml"));
// FIXME: Get root like this
BorderPane root = (BorderPane) stage.getScene().getRoot();
root.setCenter(center);


EDITED: Java codes added.

Answer

You should update the center of the existing border pane, not create a new one and set the center of the new one.

All you need is to inject the border pane into the controller in the usual way. So add a fx:id to the root element of welcome.fxml:

<!-- imports, etc... -->
<BorderPane fx:id="root" fx:controller="..." xmlns:fx="..." ... >
    <!-- ... -->
</BorderPane>

And then in the controller

public class Controller { /* or whatever name you have, again, you can't be bothered to post a MCVE */

    @FXML
    private BorderPane root ;

    @FXML
    private void buttonHandler() throws IOException {
        Pane sub = (Pane) FXMLLoader.load(getClass().getResource("../ready.fxml"));
        root.setCenter(sub);
    }

    // ...
}