javafxdividersplitpane

JavaFX Splitpane Inside of Splitpane Set Divider Positions


I am designing a JavaFX GUI in which there are multiple splitpanes embedded inside of each other. I want to be able to reset the divider positions back to their initial values if the user selects an option to reset the view. The problem is that the user has to click on the reset view option multiple times to completely reset the divider positions. Doing it once resets dividers of the same orientation, but not the dividers of opposite orientation.

Here is an example of the problem. Drag the sliders, then click the "Reset View" button at the top of the window:

public void start(Stage stage) throws Exception
{
    SplitPane mainWindow = new SplitPane();
    SplitPane leftPanel = new SplitPane();
    SplitPane rightPanel = new SplitPane();

    Button resetViewButton = new Button("Reset View");
    VBox mainFrameVBox = new VBox();
    Scene scene = new Scene(mainFrameVBox, 500, 500);

    mainWindow.setOrientation(Orientation.HORIZONTAL);
    mainWindow.getItems().addAll(leftPanel, rightPanel);
    mainWindow.setDividerPosition(0, 0.125);

    leftPanel.setOrientation(Orientation.VERTICAL);
    leftPanel.getItems().addAll(new VBox(new Text("Test 1")), new VBox(new Text("Test 2")));
    leftPanel.setDividerPosition(0, 0.5);

    rightPanel.setOrientation(Orientation.VERTICAL);
    rightPanel.getItems().addAll(new VBox(new Text("Test 3")), new VBox(new Text("Test 4")));
    rightPanel.setDividerPosition(0, 0.85);

    mainFrameVBox.getChildren().addAll(resetViewButton, mainWindow);

    VBox.setVgrow(mainWindow, Priority.ALWAYS);

    stage.setScene(scene);
    stage.show();

    resetViewButton.setOnAction(new EventHandler<ActionEvent>()
    {
       @Override
       public void handle(ActionEvent event)
       {
           mainWindow.setDividerPosition(0, 0.125);
           leftPanel.setDividerPosition(0, 0.5);
           rightPanel.setDividerPosition(0, 0.85);
       }
    });
}

I tried adding in a delay timer for each slider, which fixes the problem, but it feels like a kludgey solution. Any ideas if there is a better approach?


Solution

  • Here's what worked for me. Still kind of kludgey IMO.

        resetViewButton.setOnAction((ActionEvent event) -> {
            mainWindow.setDividerPosition(0, 0.125);
            leftPanel.setDividerPosition(0, 0.5);
            leftPanel.layout();
            rightPanel.setDividerPosition(0, 0.85);
            rightPanel.layout();
        });
    

    It seems to take multiple passes to get embedded SplitPanes to complete layout. I also tried putting the divider positioning commands the event que with Platform.runLater() as mentioned in a few similar questions, but that seemed unreliable. This works all the time for me on Windows with JavaFX 8.