我想在listview中搜索,我的代码正在工作,但不够好。问题是,当我写在搜索文本字段不仅结果出现几个字符,但也出现过项目的其余部分...JavaFX在列表视图中搜索
代码:
// Wrap the ObservableList in a FilteredList (initially display all data).
FilteredList<Client> filteredData = new FilteredList<>(main.getClientListData(),p -> true);
//Set the filter Predicate whenever the filter changes.
searchUserTF.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(client ->{
// If filter text is empty, display all persons.
if(newValue == null || newValue.isEmpty()){
return true;
}
// Compare first name and last name of every client with filter text.
String lowerCaseFilter = newValue.toLowerCase();
if(client.getFirstname().toLowerCase().contains(lowerCaseFilter)){
return true; //filter matches first name
}else if(client.getLastname().toLowerCase().contains(lowerCaseFilter)){
return true; //filter matches last name
}
return false; //Does not match
});
});
//Wrap the FilteredList in a SortedList.
SortedList<Client> sortedData = new SortedList<>(filteredData);
//put the sorted list into the listview
clientListView.setItems(sortedData);
更新! ListCell执行:
clientListView.setCellFactory(new Callback<ListView<Client>, ListCell<Client>>() {
@Override
public ListCell<Client> call(ListView<Client> param) {
final Label leadLbl = new Label();
final Tooltip tooltip = new Tooltip();
final ListCell<Client> cell = new ListCell<Client>(){
@Override
public void updateItem(Client item, boolean empty){
super.updateItem(item,empty);
if(item != null){
leadLbl.setText(item.getFirstname());
setText(item.getFirstname()+" "+item.getLastname());
tooltip.setText(item.getFirstname());
setTooltip(tooltip);
}
}
};
return cell;
}
});
谢谢,对不起英文不好!
添加代码(如果有的话)... – john16384
@ john16384添加 –