我想在多个列上对 JTable 进行排序/过滤,f.E.
Column1 Column2 一个 1 乙二 2
我想按 Column1 = b 和 Column2 = 2 对这张表进行排序。
MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
...
private void newFilter() {
RowFilter<MyTableModel, Object> rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(), 0);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
但是如何对多个列进行排序?
您可以创建 RowFilter.AndFilter 并传递您需要的所有过滤器:
List<RowFilter<M, O>> listOfFilters = new ArrayList<>();
... add filters into list
RowFilter.andFilter(listOfFilters);
只需从 RowFilter 中删除参数“0”即可对所有列进行排序:
rf = RowFilter.regexFilter(filterText.getText());
我使用了 2 个输入 JTextField(filterTextOras、filterTextClient),如果任一文本字段为空且 compoundRowFilter 都包含文本,则使用简单的 RowFilter
protected void Filtru() {
RowFilter<MyTableModel, Object> rfo = null;
RowFilter<MyTableModel, Object> rfc = null;
if(filterTextClient.getText().equals("")){
if(filterTextOras.getText().equals("")){
sorter.setRowFilter(null);
} else {
rfc = RowFilter.regexFilter(filterTextOras, 1);//column 1
sorter.setRowFilter(rfc);
}
} else {
if(filterTextOras.getText().equals("")){
rfo = RowFilter.regexFilter(filterTextClient.getText(), 0);//column 0
sorter.setRowFilter(rfo);
}
else{
List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
filters.add(RowFilter.regexFilter(filterTextClient.getText(), 0, 0));
filters.add(RowFilter.regexFilter(filterTextOras.getText(), 1));
RowFilter<Object,Object> compoundRowFilter = RowFilter.andFilter(filters);
sorter.setRowFilter(compoundRowFilter);
}
}
}