How to disable some items of javaFX ComboBox?


Question

Can someone show me how to disable some item of my combobox (With FXML or Java code)? here is my ComboBox:

<ComboBox fx:id="cBox">
  <items>
    <FXCollections fx:factory="observableArrayList">
      <String fx:value="Easy" />
      <String fx:value="Normal" />
      <String fx:value="Hard" />
    </FXCollections>
  </items>
</ComboBox>

Thanks!

1
1
11/27/2012 3:09:12 PM

Accepted Answer

i didn't found any methods that can inactive ComboBox items. You can try this work around , below code is to display sublist of items dynamically(use this idea to solve your problem).

private final ObservableList<String> allOptions = 
            FXCollections.observableArrayList("Easy","Normal","Hard");

   // method which returns sublist we need
    private ObservableList<String> getSubList(int start,int end) {

    final ObservableList<String> toBeDisplayedList = FXCollections
            .<String> observableArrayList();
    toBeDisplayedList.addAll(allOptions.subList(start, end));
    return toBeDisplayedList;
    }

   // now main logic
 if(displayAll) {
          comboBox.setItems(allOptions);
         }
 if(display only easy and normal) {
      comboBox.setItems(getSublist(0,2));
  } ...
1
11/27/2012 7:11:54 PM

I had the same issue and I think that the best solution to this problem is to use the setCellFactory(Callback,ListCell> value) method of ComboBox:

        cBox.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
        @Override
        public ListCell<String> call(ListView<String> param)
        {
            return new ListCell<String>() {
                @Override
                protected void updateItem(String item, boolean empty)
                {
                    super.updateItem(item, empty);

                    if (item != null || !empty)
                    {
                        this.setText(item);
                        this.setDisable(true); //or false
                    }
                }
            };
        }
    });

and if you want a custon ButtonCel you need to use the setButtonCell(ListCell value) Method:

        cBox.setButtonCell(new ListCell<String>() {
        @Override
        protected void updateItem(Stringitem, boolean empty)
        {
            super.updateItem(item, empty);

            if (item != null || !empty)
            {
                this.setText(item);
                this.setDisable(true); //or false
            }
        }
    });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon