Black Glix Black Glix - 9 months ago 51
Java Question

JavaFX Same textarea with different Pane's

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

, and Pane,

My start method is;

public void start(Stage primaryStage) throws Exception {

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

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

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"));

//Scene scene = new Scene(root, 640, 480);

UPDATE: Here is my mistake,as @James_D noticed, I load
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();

EDITED: Java codes added.

Answer Source

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="..." ... >
    <!-- ... -->

And then in the controller

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

    private BorderPane root ;

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

    // ...