我有一个 JTable
,它包含一个自定义 AbstractTableModel
,当调用 getValueAt
时返回一个对象。当然,我有一个自定义的 TableCellRenderer
,它能够从对象获取/构造文本,以便可以显示它。
但是现在我想写一个过滤器。过滤器将是一个简单的切换按钮。当它打开时,我希望应用过滤器,当它关闭时,我希望删除过滤器。
因此我遇到了两个问题。
第一个问题是,当您必须按对象而不是基元进行过滤时,我完全不知道如何编写过滤器。
其次,我不知道如何将所述过滤器连接到切换按钮以便能够打开和关闭它。
如果这是一个弱智问题,我很抱歉,但是 http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting是我看到的最无用的文档,因为解释不深入。
感谢任何人的帮助。
编辑:
该对象包含多个字段,但我对两个过滤器切换特别感兴趣。当我说 isSuper
时,第一个返回一个 boolean
值,而当我调用 getName
时,第二个返回一个 string
。如果第一个切换开关打开,它应该显示在 isSuper
上返回 true 的所有条目,第二个切换开关应该显示当我调用 时名称由两个单词(存在空格)组成的所有条目获取名称
。
最佳答案
说实话,JavaDocs写得很好...
由于信息如此之少,您所能期望的最好的结果就是概述......
TableRowSorter<TableModel> trs = new TableRowSorter<TableModel>();
table.setRowSorter(trs);
// Create the row filder...
trs.setRowFilter(new RowFilter<TableModel, Integer>() {
@Override
public boolean include(RowFilter.Entry<? extends TableModel, ? extends Integer> entry) {
boolean include = false;
// Returns the value for the specific column...
CustomObject value = (CustomObject)entry.getValue(filterColumn);
if (filterBySuper) {
include = value.isSuper();
} else {
include = value.getName().startsWith(fistPart) && value.getName().endWith(lastPart);
}
return include;
}
});
当你想更新过滤器时,你只需调用...
trs.sort();
关于用于过滤 jtable 行的 Java swing 切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958513/