Concatenation of both filter and orFilter for RowFilter

I have a JTable with four columns, the first of which contains either a number or text, the remaining three texts. I am trying to filter this table with a RowFilter:

sorter = new TableRowSorter<TableModel>(myOwnTableModel);

checkboxFilter I got pretty good work:

sorter.setRowFilter(RowFilter.regexFilter("^[0-9]$", 0));

This sorter is activated or deactivated depending on the checkbox selected or not checked.
The second filtering occurs if the user places the text in a text field. For myself, this already works great:

String regex = "(?i)" + Pattern.quote(s); // s = input Text of user
sorter.setRowFilter(RowFilter.regexFilter(regex, 1,2,3));

What I cannot do is activate both filters at the same time. Perhaps I’m thinking too much, my idea was to "concatenate" two filters, the Filter should be "and" another "or" checkbox. I tried several things, for me something like the most promising looked:

String regex = "(?i)" + Pattern.quote(s);
bookFilter = RowFilter.regexFilter(regex, 1,2,3);
sorter.setRowFilter(bookFilter.andFilter(Arrays.asList(
                    RowFilter.regexFilter("^[0-9]$", 0))));

Unfortunately, this does not lead to a useful result. Any ideas appreciated :)

+3
source share
1 answer

The solution is to add ActionListenerin JCheckBoxto update the filter state if the check box is selected, and add DocumentListenerto the JTextFieldbase document to update the filter state if the contents of the field are updated.

, andFilter bookFilter (.. andFilter). :

RowFilter andFilter = RowFilter.andFilter(filter1, filter2, etc);

JCheckBox cb = ...
cb.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    updateFilters();
  }
});

JTextField tf = ...
tf.getDocument().addDocumentListener(new DocumentListener() {
  public void insertUpdate(DocumentEvent e) { updateFilters(); }
  public void removeUpdate(DocumentEvent e) { updateFilters(); }
  publci void changedUpdate(DocumentEvent e) { updateFilters(); }
});

... updateFilters() , , .

public void updateFilters() {
  if (cb.isSelected()) {
    if (tf.getText().length() > 0) {
       // Both filters active so construct an and filter.
       sorter.setRowFilter(RowFilter.andFilter(bookFilter, checkBoxFilter));
    } else {
       // Checkbox selected but text field empty.
       sorter.setRowFilter(checkBoxFilter);
    }
  } else if (tf.getText().length() > 0) {
    // Checkbox deselected but text field non-empty.
    sorter.setRowFilter(bookFilter);
  } else {
    // Neither filter "active" so remove filter from sorter.
    sorter.setRowFilter(null); // Will cause table to re-filter.
  }
}
+4

Source: https://habr.com/ru/post/1775865/


All Articles