Accordion in JavaFX Controls

By Doug Lowe

An accordion in JavaFX is a stack of titled panes. Only one of the titled panes in the accordion can be opened at any given moment. So if one of the titled panes in the accordion is open and you open a different one, the one that was open automatically closes.

This figure shows an accordion pane that contains three title panes; the same accordion pane is shown three times in the figure, each time with a different one of the titled panes opened.

An accordion control in JavaFX.

An accordion control in JavaFX.

To create an accordion control, you first create the separate titled panes that will make up the accordion. Then, you create the accordion using the default constructor and add the titled panes using the getPanes().addAll method. The following code sample shows how to create the accordion shown in the figure:

// Create the size toggle pane
RadioButton rbSmall = new RadioButton("Small");
RadioButton rbMedium = new RadioButton("Medium");
RadioButton rbLarge = new RadioButton("Large");
ToggleGroup sizeGroup = new ToggleGroup();
sizeGroup.getToggles().addAll(rbSmall, rbMedium, rbLarge);
VBox sizeBox = new VBox(10);
sizeBox.setPadding(new Insets(10));
sizeBox.getChildren().addAll(rbSmall, rbMedium, rbLarge);
TitledPane sizeTpane = new TitledPane("Size", sizeBox);
// Create the style toggle pane
RadioButton rbThin = new RadioButton("Thin crust");
RadioButton rbThick = new RadioButton("Thick crust");
ToggleGroup styleGroup = new ToggleGroup();
styleGroup.getToggles().addAll(rbThin, rbThick);
VBox styleBox = new VBox(10);
styleBox.setPadding(new Insets(10));
styleBox.getChildren().addAll(rbThin, rbThick);
TitledPane styleTpane = new TitledPane("Style", styleBox);
// Create the toppings toggle pane
CheckBox cbPepperoni = new CheckBox("Pepperoni");
CheckBox cbSausage   = new CheckBox("Sausage");
CheckBox cbOlives    = new CheckBox("Olives");
CheckBox cbMushrooms = new CheckBox("Mushrooms");
CheckBox cbAnchovies = new CheckBox("Anchovies");
VBox toppingsBox = new VBox(10);
toppingsBox.setPadding(new Insets(10));
toppingsBox.getChildren().addAll(cbPepperoni, cbSausage,
    cbOlives, cbMushrooms, cbAnchovies);
TitledPane toppingsTpane = new TitledPane("Toppings", toppingsBox);
// Create the accordion control
Accordion acc = new Accordion();
acc.getPanes().addAll(sizeTpane, styleTpane, toppingsTpane);