javaguy
javaguy

Reputation: 11

Java FX How to Enable a ComboBox if a CheckBox is selected?

I'm a new Java user and I'm currently working on a program and need a way to enable a ComboBox when a CheckBox is selected. The ComboBox must also be disabled unless that CheckBox is checked.

I'm trying to have it so the ComboBox is disabled (and basically darkened out and not able to be used) unless that corresponding CheckBox is clicked, and I'm trying to use if statements to get this done but not sure what to do next.

        if (chkBuildCourse.isSelected())
        {
            instructorIsComboBox.
        }

        else if (chkNewInstructor.isSelected())
        {
            addInstructorComboBox.
        }

Upvotes: 0

Views: 435

Answers (3)

b3tuning
b3tuning

Reputation: 347

bindings make this an easy task... bind yourComboBox disableProperty to yourCheckBox selectedProperty and invert it with a not() like so

        instructorIsComboBox.disableProperty().bind(chkBuildCourse.selectedProperty().not());
        instructorIsComboBox.editableProperty().bind(chkBuildCourse.selectedProperty());
        addInstructorComboBox.disableProperty().bind(chkNewInstructor.selectedProperty().not());
        addInstructorComboBox.editableProperty().bind(chkNewInstructor.selectedProperty());

(edited to hopefully match your code fragment)

now the yourComboBox is disabled whenever the yourCheckBox is not selected. You can also bind the visibleProperty, editable, managed, etc to other controls to reduce boiler clutter.

Upvotes: 0

Fabian Zimbalev
Fabian Zimbalev

Reputation: 553

Using your approach:

instructorIsComboBox.setEditable(chkBuildCourse.isSelected());

You don´t need if statements since the "isSelected()" method returns a boolean and the setEditable takes one.

Using a listener

myCheckbox.selectedProperty().addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<? extends Boolean> observable, Boolean oldVal, Boolean newVal) {
        myComboBox.setEditable(newVal);
    }
});

https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ComboBoxBase.html#setEditable-boolean-

Upvotes: 0

Try it:

public class Controller implements Initializable {

@FXML
private ComboBox<?> cbb;

@FXML
private CheckBox cb;

@Override
public void initialize(URL location, ResourceBundle resources) {
    comboBox.setOnAction(event -> checkBox.setDisable(!cb.isSelected()));
}}

Upvotes: 1

Related Questions