Search code examples
javafxscenesplitpane

Accessing the panes inside a scene in JavaFX?


I found here some similar questions, but none of them seem to be a solution to my problem.

How can I access the different panes in the structure of a scene?

The goal would be:

I have a split pane in the scene, which is put on to a border pane. In the left anchor pane of the split pane I would like to have an accordion. The right side should display a scene according to the chosen menu point of the accordion.

So if it would be possible to set a scene into the right side of the split pane it would be good, because than I could change this scene. Changing the whole scene is not a very good solution, cause the accordion won't be opened there where it was, and the app consumes too many fxml files.

Is it possible to only change the right side of the split pane, or is my approach completely wrong?

I found here how to get all Nodes in a scene, but it didn't bring me further.

Please give me an advice if you have experience with it, thanks!


Solution

  • Assuming you just have two nodes in the split pane, you can replace the second (right) one with

    splitPane.getItems().set(1, newNode);
    

    (Update)

    If your SplitPane is defined in an FXML file, you will need to do this in the controller. To get access to the split pane, just give it an fx:id attribute (in SceneBuilder this is in the "code" section in the right panel) and use an @FXML annotation to inject it into the controller:

    FXML file:

    <!-- imports omitted -->
    <AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.MyController">
       <SplitPane fx:id="mainSplitPane">
          <!-- ... -->
       </SplitPane>
    </AnchorPane>
    

    MyController.java:

    package com.example ;
    
    // imports omitted...
    
    public class MyController {
    
        @FXML
        private SplitPane mainSplitPane ;
    
        @FXML
        private void handleButtonPress() {
            Node newNode = ... ;
            mainSplitPane.getItems().set(1, newNode);
        }
    
        // ...
    }