The check box allows users to do multiple selections. For example, when ordering pizza we can add more than one toppings. The radio button or the toggle button are for single choice or no choice.
We can use constructors from CheckBox to create objects of CheckBox.
To create a checkbox without a caption
CheckBox checkBox = new CheckBox();
To create a checkbox with a string caption
CheckBox checkBox = new CheckBox("Second");
After creating a checkbox, we can change its text and make it selected.
checkBox.setText("First");
checkBox.setSelected(true);
We can use CheckBox to represent three states:
The "Not Applicable" state is call Indeterminate. If the CheckBox is not in the Indeterminate, it can be selected or not-selected. Selected means Yes and not-selected means No.
We can choose to support the Indeterminate by setting the allowIndeterminate property of the CheckBox object.
If set to true the checkbox should cycle through all three states: selected, deselected, and undefined.
If set to false, the checkbox will cycle through the selected and deselected states.
The following code shows how to add tooltip to CheckBox.
import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; // w w w. j a va 2 s . co m public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { Scene scene = new Scene(new Group()); stage.setTitle("Tooltip Sample"); stage.setWidth(300); stage.setHeight(150); final CheckBox cb = new CheckBox("checkBox"); final Tooltip tooltip = new Tooltip("$ tooltip"); tooltip.setFont(new Font("Arial", 16)); cb.setTooltip(tooltip); cb.selectedProperty().addListener(new ChangeListener<Boolean>() { public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { System.out.println(cb.isSelected()); } }); ((Group) scene.getRoot()).getChildren().add(cb); stage.setScene(scene); stage.show(); } }
The code above generates the following result.