编辑:我试图构建一个带有搜索功能的组合框,这就是我想出的:
public class SearchableComboBox<T> extends ComboBox<T> {
private ObservableList<T> filteredItems;
private ObservableList<T> originalItems;
private T selectedItem;
private StringProperty filter = new SimpleStringProperty("");
public SearchableComboBox () {
this.setTooltip(new Tooltip());
this.setOnKeyPressed(this::handleOnKeyPressed);
this.getTooltip().textProperty().bind(filter);
this.showingProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
// If user "closes" the ComboBox dropdown list: reset filter, reset list to the full original list, hide tooltip
if (newValue == false) {
filter.setValue("");;
setItems(originalItems);
getTooltip().hide();
// If user opens the combobox dropdown list: get a copy of the items and show tooltip
} else {
originalItems = getItems();
Window stage = getScene().getWindow();
getTooltip().show(stage);
}
}
});
}
public void handleOnKeyPressed(KeyEvent e) {
//Only execute if the dropdown list of the combobox is opened
if (this.showingProperty().getValue() == true) {
// Get key and add it to the filter string
String c = e.getText();
filter.setValue(filter.getValue() + c);
//Filter out objects that dont contain the filter
this.filteredItems = this.originalItems.filtered(a -> this.getConverter().toString(a).toLowerCase().contains(filter.getValue().toLowerCase()));
//Set the items of the combox to the filtered list
this.setItems(filteredItems);
}
}
这个想法很简单:只要打开组合框的下拉列表,我就会监听按键并将字符添加到过滤器中。使用这些过滤器,组合框的项目列表被过滤为仅包含包含过滤字符串的项目的列表。然后我使用 setItems 将项目列表设置为我的过滤列表。我的问题是,组合框的 valueProperty 更改,但我希望所选对象保持不变,直到用户从下拉列表中选择另一个。
白板的微信
森栏
相关分类