通过 ButtonClick 隐藏 JTable 中的多个元素

Hiding Multiple Elements in JTable via ButtonClick

我目前正在开发一种在 JTable 中动态编辑数据的工具。每当单击按钮时,我都想隐藏目标行。现在我正在使用 RowFilter。每当单击按钮时,都会创建一个新过滤器:

            RowFilter<MyTableModel, Object> rowFilter = null;
        try {
            rowFilter = RowFilter.notFilter(RowFilter.regexFilter(((String)dataTable.getValueAt(dataTable.getSelectedRow(), 0)),0));

        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rowFilter);

每次单击按钮时,这只对一个元素有效。我想让它们隐藏起来,这样你就可以不断地隐藏 table 中的元素。重要的是要提到我不想删除行,只是隐藏它们。

我希望有人对此有一个简单的答案,现在已经找了一段时间了。

此方法 sorter.setRowFilter(rowFilter); 会在您每次 "add" 新过滤器时更换过滤器。所以,这是 "forgetting" 旧规则。您需要做的是编辑现有过滤器以包含新的过滤规则。

查看 documentation 了解更多详情。

无论如何,我提取了您应该尝试实现的文档的一部分。

来自 RowFilter Javadoc:

Subclasses must override the include method to indicate whether the entry should be shown in the view. The Entry argument can be used to obtain the values in each of the columns in that entry. The following example shows an include method that allows only entries containing one or more values starting with the string "a":

RowFilter<Object,Object> startsWithAFilter = new RowFilter<Object,Object>() {
   public boolean include(Entry<? extends Object, ? extends Object> entry) {
     for (int i = entry.getValueCount() - 1; i >= 0; i--) {
       if (entry.getStringValue(i).startsWith("a")) {
         // The value starts with "a", include it
         return true;
       }
     }
     // None of the columns start with "a"; return false so that this
     // entry is not shown
     return false;
   }
 };

这意味着 include() 方法将 return truefalse 取决于是否应显示项目。

因此,您应该只设置一次 RowFilter,然后重新实现 include() 方法以匹配您当前在视图中设置的所有规则。