简体   繁体   English

有没有办法检查ComboBox在JavaFX中是否有任何项目?

[英]Is there a way to check if a ComboBox has any items in JavaFX?

Is there a way to check if a ComboBox has any items in it or whether it is empty? 有没有一种方法可以检查ComboBox是否有任何项目或它是否为空? 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. 我有一个ComboBox数组,我需要遍历每个数组,如果ComboBox中没有任何项目,那么我必须将其隐藏。 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是否没有项目的代码正确,但是用于隐藏ComboBox代码却不正确。

ComboBox.hide only closes the popup showing the items, if it's open. ComboBox.hide如果打开,则仅关闭显示项目的弹出窗口。 It does not hide the ComboBox . 它不会隐藏ComboBox To hide the ComboBox , you need to set the visibility: 要隐藏ComboBox ,您需要设置可见性:

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: 或者调用一个方法来隐藏ComboBox ES,你可以绑定visibleProperty中的ComboBox下载到自己的itemsProperty使用自定义绑定:

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. 好处是,您无需调用任何方法来隐藏ComboBox ,因为绑定是自动评估的,因此没有人可以看到您的空组合。

The .getItems() method returns an ObservableList<T> so you can just check its .size() . .getItems()方法返回一个ObservableList<T>因此您只需检查其.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. 如果ComboBox由自己的List填充,则您也可以仅通过相同的.size()调用检查列表是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM