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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With