简体   繁体   中英

How to collapse TitledPane programmatically in JavaFX?

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

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 TitledPane s 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM