Reputation: 11
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
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
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);
}
});
Upvotes: 0
Reputation: 491
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