2

I have a ComboBox which I'm populating with Sheet object values.

I set a Cell Factory in order to display the sheet's name in the drop down list itself. It works properly (seems so).

The problem is that after an item ("Cell") is selected, the value that is shown in the box is not the value that was shown in the list.

This is the relevant code part:

excelFile = new ExcelFile(file);            
//ObservableList<String> sheets = FXCollections.observableArrayList(excelFile.getSheetsNames());
ObservableList<Sheet> sheets = FXCollections.observableArrayList(excelFile.getSheets());

sheetsBox.setItems(sheets);
sheetsBox.setDisable(false);            

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

                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(item.getSheetName());
                }
            }        
        };
    }
});

This is the problem (visually): enter image description here Thank you

Ido Gal
  • 528
  • 10
  • 26

1 Answers1

7

The cell used to display the selected item is the buttonCell. So you just need to set the same cell for the button cell. You can factor the cell creation into a method to avoid replicating code:

sheetsBox.setCellFactory(lv -> createSheetCell());
sheetsBox.setButtonCell(createSheetCell());

// ...

private ListCell<Sheet> createSheetCell() {
    return new ListCell<Sheet>() {
        @Override
        protected void updateItem(Sheet item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null) {
                setText(null);
                setGraphic(null);
            } else {
                setText(item.getSheetName());
            }
        }        
    };
}
James_D
  • 201,275
  • 16
  • 291
  • 322