我想在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添加 –