How to collapse TitledPane programmatically in JavaFX?


Question

Does anyone know how to programmatically collapse a TitledPane in JavaFX? I know the methods setExpanded and setCollapsible are available but it only enables the property. I want to collapse the pane without any mouse interaction.

    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });

    TitledPane titledPane = new TitledPane();
    titledPane.setAnimated(true);
    titledPane.setText("This is a test");
    titledPane.setContent(btn);
    titledPane.setExpanded(true);

    Accordion accordion = new Accordion();
    accordion.getPanes().add(titledPane);

    Button show = new Button("Expand");
    show.setOnAction((ActionEvent event) -> {
        accordion.setExpandedPane(titledPane); // Expanded Pane works!
    });

    Button hide = new Button("Collapse");
    hide.setOnAction((ActionEvent event) -> {
        //???
    });

    HBox layout = new HBox(10);
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");
    layout.getChildren().addAll(show, hide, accordion);
    Scene scene = new Scene(layout, 320, 240);
    scene.setFill(Color.GHOSTWHITE);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

Here is the result I am looking for

1
2
1/23/2019 2:17:15 AM

Accepted Answer

Since only one TitledPane in the same Accordion can be expanded at any time, the Accordion (to some extent) manages the expanded state of any TitledPanes it contains.

You can do

accordion.setExpandedPane(titledPane);

to get the accordion to expand titledPane.

Calling titledPane.setExpanded(true); also works, but only if you invoke this after the window has been shown (for reasons I don't fully understand).

8
11/18/2014 5:04:28 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon