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");
tb1.setToggleGroup(group);
tb1.setSelected(true);

ToggleButton tb2 = new ToggleButton("Medium");
tb2.setToggleGroup(group);

ToggleButton tb3 = new ToggleButton("Low");
tb3.setToggleGroup(group);




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.

tb1.setUserData("High");
tb2.setUserData("Medium");
tb3.setUserData("Low");

ToggleGroup group = new ToggleGroup();

group.selectedToggleProperty().addListener            
    (ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) -> {
    if (new_toggle == null)
        System.out.println("default value");
    else
        System.out.println(group.getSelectedToggle().getUserData());
});

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.

.toggle-button1{
    -fx-font: 30 arial; 
    -fx-base: green;   
}
 
.toggle-button2{
    -fx-font: 25 arial; 
    -fx-base: blue;  
}
 
.toggle-button3{
    -fx-font: 30 arial; 
    -fx-base: red;   
}

Second, we install the styles in the application.

scene.getStylesheets().add("myStyle.css");

tb1.getStyleClass().add("toggle-button1");
tb2.getStyleClass().add("toggle-button2");
tb3.getStyleClass().add("toggle-button3");