原始问题地址:
https://stackoverflow.com/questions/42519911/execute-code-on-filtering-javafx-tableview-rows
主要思路
用FilteredList类,调用setPredicate函数获取满足条件的数据.
然后使用SortedList排序数据,最后调用comparatorProperty().bind函数将数据绑定到
TableView
步骤说明:
1.使用TableView数据源 distanceDatas 创建filteredData实例
FilteredList<DistanceModel> filteredData = new FilteredList<>(distanceDatas, p -> true);
2.对过滤条件的输入框进行监听
distanceFilterField.textProperty().addListener((observable, oldValue, newValue) -> { filteredData.setPredicate(commande -> { int lowerCaseFilter=0; try { lowerCaseFilter = Integer.valueOf(newValue); } catch(Exception e) { LogUtil.error(newValue+" 过滤条件不是整数"); return true; } //偏移距离大于输入值则显示 if (Double.valueOf(commande.getDistance().get())>lowerCaseFilter) { return true; // Filter matches first name. } }) }
filteredData.setPredicate把满足条件的数据获取出来,返回true
3.对筛选的数据进行排序
SortedList<DistanceModel> sortedData = new SortedList<>(filteredData);
4.将数据绑定到TableView
sortedData.comparatorProperty().bind(distanceTableView.comparatorProperty()); // 5. Add sorted (and filtered) data to the table. distanceTableView.setItems(sortedData);
下面是完整代码:
//丢星表数据
private ObservableList<DistanceModel> distanceDatas;
// 偏移距离表
@FXML
TableView distanceTableView;
//偏移距离大于输入值则显示
@FXML
TextField distanceFilterField;
/**
* 过滤偏移距离
* 偏移距离大于输入值则显示
* 实现表格过滤行:
* https://stackoverflow.com/questions/42519911/execute-code-on-filtering-javafx-tableview-rows
*/
public void filterDistance()
{
//偏移距离数据
FilteredList<DistanceModel> filteredData = new FilteredList<>(distanceDatas, p -> true);
// 2. Set the filter Predicate whenever the filter changes.
distanceFilterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(commande -> {
LogUtil.info("[filterField.textProperty()]");
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}
// Compare first name and last name of every person with filter text.
int lowerCaseFilter=0;
try
{
lowerCaseFilter = Integer.valueOf(newValue);
}
catch(Exception e)
{
LogUtil.error(newValue+" 过滤条件不是整数");
return true;
}
//偏移距离大于输入值则显示
if (Double.valueOf(commande.getDistance().get())>lowerCaseFilter) {
return true;
// Filter matches first name.
}/* else if (String.valueOf(commande.getCMD()).toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
}
else if (String.valueOf(commande.getClient()).toLowerCase().contains(lowerCaseFilter)) {
return true; // Filter matches last name.
}
*/
return false; // Does not match.
});
// 3. Wrap the FilteredList in a SortedList.
SortedList<DistanceModel> sortedData = new SortedList<>(filteredData);
// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(distanceTableView.comparatorProperty());
// 5. Add sorted (and filtered) data to the table.
distanceTableView.setItems(sortedData);
});
}
代码运行效果