CheckBox
A CheckBox is a UI element that lets the user choose YES or NO.
Examples:
β Accept terms β¬ Subscribe to newsletter
π It has only two states:
- Checked β true
- Unchecked β false
1οΈβ£ FXML: Define a CheckBox
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="20" alignment="CENTER" xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.CheckBoxController">
<CheckBox text="Accept Terms" fx:id="termsCheckBox" onAction="#handleCheckBoxAction"/>
</VBox>
Explanation:
fx:id="termsCheckBox"β lets the controller access this checkbox.onAction="#handleCheckBoxAction"β calls the method in the controller when the checkbox is clicked (checked or unchecked).
2οΈβ£ Controller: Handle the CheckBox
package com.example;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
public class CheckBoxController {
@FXML
private CheckBox termsCheckBox;
@FXML
private void handleCheckBoxAction() {
if (termsCheckBox.isSelected()) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("CheckBox Selected");
alert.setHeaderText(null);
alert.setContentText("You accepted the terms.");
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("CheckBox Unselected");
alert.setHeaderText(null);
alert.setContentText("You did not accept the terms.");
alert.showAndWait();
}
}
}
Explanation:
termsCheckBox.isSelected()β checks if the checkbox is checked.- We show an Alert depending on whether itβs checked or not.
3οΈβ£ Main Class: Load the FXML
package com.example;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("checkbox_layout.fxml"));
Scene scene = new Scene(loader.load(), 300, 200);
stage.setScene(scene);
stage.setTitle("CheckBox Example");
stage.show();
}
public static void main(String[] args) {
launch();
}
}
β Key Notes:
- Use
isSelected()to check the state of a CheckBox. - Use
setSelected(true/false)if you want to change the state programmatically. onActionfires every time the user clicks the checkbox, whether checking or unchecking.