FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

JavaFX Toggle Buttons

Code Description:

Easy code for displaying a fully functional toggle button that will perform different actions whether the button is selected or deselected.

Toggle Button Syntax:

ToggleButton toggleButton = new ToggleButton("Button Text");
		
toggleButton.setOnAction(new EventHandler<ActionEvent>() {
			
    @Override
    public void handle(ActionEvent event) {
				
        if (toggleButton.isSelected() == true) {
            // Actions to perform when toggle button is selected
	} else {
            // Actions to perform when toggle button is deselected
	}
				
    }
});

Runnable JavaFX Toggle Button Example Code:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Demo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
		
        VBox root = new VBox();
		
	ToggleButton lightSwitchToggleButton = new ToggleButton("Light Switch On");
		
	lightSwitchToggleButton.setOnAction(new EventHandler<ActionEvent>() {
			
	    @Override
	    public void handle(ActionEvent event) {
				
	        if (lightSwitchToggleButton.isSelected() == true) {
		    lightSwitchToggleButton.setText("Light Switch Off");
		    root.setStyle("-fx-background-color: yellow;");
		} else {
		    lightSwitchToggleButton.setText("Light Switch On");
		    root.setStyle("-fx-background-color: white;");
		}
				
	    }
        });
		
		
        root.getChildren().add(lightSwitchToggleButton);
		
        primaryStage.setTitle("Toggle Button Demo");
        primaryStage.setScene(new Scene(root, 200, 100));
        primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

In the example, when the Toggle Button is selected, we change the button text and the color of the root background to yellow.

JavaFX Toggle Button Selected Output Image

In the example, when the Toggle Button is deselected, we change the button text again and the color of the root background back to white.

JavaFX Toggle Button Deselected Output Image

Important Methods:

  • isSelected() - Used to determine if the toggle button is selected or not.
  • setSelected() - Used to set the button into a toggled state. Remember that doing this will NOT call the code in the event handler.
  • fire() - Used to programatically "press" a toggle button without any user interaction. Use this if you need to call the code in the event handler.
  • getText() - Used to get the text displayed on the toggle button.
  • setDisable() - Used to make the toggle button grayed out and unclickable. EX: "toggleButton.setDisable(true);"
  • setFont() - Set the font and font size for the toggle button text. EX: "toggleButton.setFont(new Font("Courier New", 20));"
  • setPrefSize() - Set the preferred width and height for the toggle button.
  • setOnAction() - Set the code and event handler for when the toggle button is clicked or pressed.
  • setText() - Set the text displayed on the toggle button.
  • setStyle() - Set an inline CSS-like style on the toggle button. EX: "toggleButton.setStyle("-fx-background-color: green;");"
  • setTooltip() - Set a message that displays when a user hovers over the toggle button control for a certain amount of time. EX: "toggleButton.setTooltip(new Tooltip("Press Me"));"
  • setVisible() - Show or hide a toggle button from the scene. EX: "toggleButton.setVisible(false);"

Related Links:

JavaFX Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes