I adapted Jonathan Stenbackas Answer (JavaFX - Filtered ComboBox) to a ComboBox with a Jooq Record Bean, displaying one of the Beans fields using a custom ListCell/ButtonCell. The filtering works fine, but I can't get the Editor to show the text of the selected items field.
I added a listener to the combobox' selection and let it print out editors Text. So I get the toString() of the bean, but the Editor is empty. When I use the listener to set the text programmatically, the programmatically set text is printed out, but the editor does not show it. I also tried a JavaFX bean for testing, with the same result. Any recommendation would be highly appreciated.
//retrieving data from database
ObservableList<MyRecord> items = applicationContext.getFetchData().fetchOList();
//wrapping in a FilteredList
FilteredList<MyRecord> filteredItems = new FilteredList<>(items, p -> true);
ComboBox<MyRecord> cb = new ComboBox<>(filteredItems);
cb.setEditable(true);
cb.setCellFactory(c_ -> new NamenCell());
cb.setButtonCell(new NamenCell());
TextField editor = cb.getEditor();
editor.textProperty().addListener((obs, oldValue, newValue) -> {
final MyRecord selected = cb.getSelectionModel().getSelectedItem();
Platform.runLater(() -> {
if (selected == null || !selected.getSurname().equals(editor.getText())) {
filteredItems.setPredicate(item -> {
if (item.getSurname().toLowerCase().contains(newValue.toLowerCase())) {
return true;
} else {
return false;
}
});
}
});
});
cb.getSelectionModel().selectedItemProperty().addListener(
(ob, oldValue, newValue) -> {
if (newValue != null) {
cb.getEditor().setText(newValue.getSurname());
System.out.println(cb.getEditor().getText());
}
});
//The Cell class:
public class NamenCell extends ListCell<MyRecord> {
public NamenCell() { }
@Override
protected void updateItem(MyRecord item, boolean empty) {
super.updateItem(item, empty);
setText(item == null ? "" : item.getSurname());
}
}