Is there a way to check if a ComboBox
has any items in it or whether it is empty? I have an array of ComboBox
es and I need to go through each of them, if there are no items in the ComboBox
, then I must hide it. This following code doesn't seem to work:
for (ComboBox cmb : comboBoxes) {
if (cmb.getItems().isEmpty()) {
cmb.hide();
}
}
The code for checking, if the ComboBox
has no items is correct, you code for hiding the ComboBox
es is incorrect however.
ComboBox.hide
only closes the popup showing the items, if it's open. It does not hide the ComboBox
. To hide the ComboBox
, you need to set the visibility:
for (ComboBox cmb : comboBoxes) {
if (cmb.getItems().isEmpty()) {
cmb.setVisible(false);
}
}
Alternatively to call a method to hide the ComboBox
es, you can bind the visibleProperty
of the ComboBox
es to their own itemsProperty
with a custom binding:
List<ComboBox<String>> comboBoxes = new ArrayList<>();
for(int i = 0; i< 10; i++) {
ComboBox<String> combo = new ComboBox<>();
combo.visibleProperty().bind(Bindings.createBooleanBinding(() -> !combo.getItems().isEmpty(),
combo.itemsProperty().get()));
comboBoxes.add(combo);
}
The advantage is, that you don't have to call any methods to hide your ComboBox
es, because the binding is evaluated automatically, therefore no one can see your empty combos.
The .getItems()
method returns an ObservableList<T>
so you can just check its .size()
. This will tell you if it's empty.
for (ComboBox cmb : comboBoxes) {
if (cmb.getItems().size() <= 0) { // or cmb.getItems().isEmpty()
cmb.setVisible(false); }
}
If the ComboBox
is populated by a List
of its own, you could also just check if the list is empty with the same .size()
call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.