Jonas
Jonas

Reputation: 3

Hiding Multiple Elements in JTable via ButtonClick

I am currently working on a tool which edits data dynamically in a JTable. I want to hide the targeted row whenever a button is clicked. Right now I am using RowFilter. Whenever the button isClicked, a new filter is created:

            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);

This only works for one element each time the button is clicked. I want to stay them hidden, so you can continously hide elemtens in the table. It is important to mention that I do not want to delete the rows, just hide them.

I hope someone has an easy answer for this, looking for quite a while now.

Upvotes: 0

Views: 63

Answers (1)

mr.celo
mr.celo

Reputation: 585

This method sorter.setRowFilter(rowFilter); is replacing the filter every time you "add" a new filter. So, it's "forgetting" the old rules. What you have to do is edit the existing filter to include the new rules for filtering.

Check out the documentation for more details.

In any case, I extracted a part of the documentation which you should try to implement.

From 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;
   }
 };

This means that the include() method is going to return true or false depending if an item should be shown.

Therefore, you should only set the RowFilter once, and reimplment the include() method to match all the rules you currently have set upon your view.

Upvotes: 2

Related Questions