Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse TitledPane programmatically in JavaFX?

Tags:

java

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

like image 854
mgaholland Avatar asked Nov 18 '14 16:11

mgaholland


1 Answers

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

like image 114
James_D Avatar answered Oct 28 '22 00:10

James_D