JavaFX Tutorial - JavaFX ToggleButton

A toggle button has two states: selected or not selected.

We normally combine two or more toggle buttons into a group and allow user to select only one button or none.

Creating a Toggle Button

We can create a toggle button by using the three constructors of the ToggleButton class.

To create a toggle button without any caption or icon

ToggleButton tb = new ToggleButton();

To create a toggle button with a text caption

ToggleButton tb = new ToggleButton("Press me");

To create a toggle button with a text caption and an icon

Image image = new Image(getClass().getResourceAsStream("icon.png"));
ToggleButton tb = new ToggleButton ("Press me", new ImageView(image));

setText method can set the text to a ToggleButton and setGraphic method can install image to a ToggleButton.

Toggle Button Group

A toggle group does not force to select at least one button. Clicking the selected toggle button deselects the toggle button.

ToggleGroup group = new ToggleGroup();

ToggleButton tb1 = new ToggleButton("High");

ToggleButton tb2 = new ToggleButton("Medium");

ToggleButton tb3 = new ToggleButton("Low");

ToggleButton Behavior

The setUserData method associates user value to a toggle button.

The ChangeListener object checks a selected toggle in the group. If none of the toggle buttons is selected, output default value.

If one of the toggle button is selected, the getSelectedToggle and getUserData methods return the user defined value.


ToggleGroup group = new ToggleGroup();

    (ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) -> {
    if (new_toggle == null)
        System.out.println("default value");

Styling Toggle Buttons

We can apply CSS styles to the toggle buttons.

First, we declare the styles of the toggle buttons in the myStyle.css file.

    -fx-font: 30 arial; 
    -fx-base: green;   
    -fx-font: 25 arial; 
    -fx-base: blue;  
    -fx-font: 30 arial; 
    -fx-base: red;   

Second, we install the styles in the application.