I want to search in listview and my code is working but not well enough. The problem is when i write few characters in the search text field not only the result appears, but the rest of the items also appear…
The code:
// 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 implementation:
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; } });
Advertisement
Answer
Your problem is not in your filter logic.
I think you have a bad ListCell
implementation that does not clear its text when it is supposed to display nothing.
Update
Yeah, your cell renderer does not clear the cell when the item is null
. Try something like this:
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); } else { leadLbl.setText(""); setText(""); } } };