我实现了一个简单的
TableFilterPanel
在过去有一个
JTextField
当给定字段中存在文本时,执行正则表达式匹配。我通常把它列为一个垂直标签+文本字段的列表(也就是说,它相当紧凑)。
我的主课叫
ColumnSearcher
,它提供了制造
RowFilter
使用
文本框
:
protected class ColumnSearcher {
private final int[] columns;
private final JTextField textField;
public ColumnSearcher(int column, JTextField textField) {
this.columns = new int[1];
this.textField = textField;
this.columns[0] = column;
}
public JTextField getTextField() {
return textField;
}
public boolean isEmpty() {
String txt = textField.getText();
return txt == null || txt.trim().length() == 0;
}
/**
* @return Filter based on the associated text field's value, or null if the text does not compile to a valid
* Pattern, or the text field is empty / contains whitespace.
*/
public RowFilter<Object, Object> createFilter() {
RowFilter<Object, Object> ftr = null;
if (!isEmpty()) {
try {
ftr = new RegexFilter(Pattern.compile(textField.getText(), Pattern.CASE_INSENSITIVE), columns);
} catch(PatternSyntaxException ex) {
// Do nothing.
}
}
return ftr;
}
}
当我想更改过滤器设置时,我从每个单独的过滤器构建一个“和”过滤器:
protected RowFilter<Object, Object> createRowFilter() {
RowFilter<Object, Object> ret;
java.util.List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>(columnSearchers.length);
for (ColumnSearcher cs : columnSearchers) {
RowFilter<Object, Object> filter = cs.createFilter();
if (filter != null) {
filters.add(filter);
}
}
if (filters.isEmpty()) {
ret = NULL_FILTER;
} else {
ret = RowFilter.andFilter(filters);
}
return ret;
}
通常我会发射
PropertyChangeEvent
当我希望更新筛选器并让PropertyChangeListener响应它并重新生成聚合筛选器时。然后您可以选择启动“rowFilter”
属性更改事件
如果用户键入其中一个文本字段(例如,通过添加
DocumentListener
对每个人
文本框
).
希望能有所帮助。