How to ... / FAQs
- How to create a table filter
- Listening for sorting events
- Create additional user filters
- Avoiding sudden row vanishing while editing
- How to create a table filter
The header section describes the usage of the TableFilterHeader class, that defines the filter header associated to tables.
As summary: create first the JTable, that should be included in a JScrollPane, as it is usual. Then, just create the TableFilterHeader with the table as single parameter -other constructors can be invoked to modify the default behaviour-.
JTable table = new JTable(); /* ... JScrollPane scrollPane = new JScrollPane(table); ...*/ TableFilterHeader filter = new TableFilterHeader(table);
This code is enough to start using the table filter. Check then its javadoc to customize it, or check the examples, whose code is available in the download section - use the source distribution file-
- Listening for sorting events
Listening for sorting events require adding a listener to the table itself. For example, it is possible to add a tooltip that shows the current number of rows -or how many have been filtered out-:
header.getTable().getRowSorter().addRowSorterListener(new RowSorterListener() { @Override public void sorterChanged(RowSorterEvent e) { System.out.println(e.getPreviousRowCount()); } });
- Create additional user filters
It is easy to define additional filters outside the header filter, subclassing from the
Filter class, for example: final Filter userFilter = new Filter(){ @Override public boolean include(Entry entry) { return -1!=entry.getStringValue(nameColumn).indexOf('e'); } }; filterHeader.addFilter(userFilter); JCheckBox check = new JCheckBox("Filter out any row where the "+ "name does not contain a lower case 'e'"); check.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { userFilter.setEnabled(e.getStateChange()==ItemEvent.SELECTED); } });
- Avoiding sudden row vanishing while editing
When a user edits a given table's row, it could happen that the row does not match anymore the filters that the user specified. Being this the case, the row should dissapear from the current view, but this can be, at the very least, quite confusing for the user: modifying a column makes the row vanish!
The solution -if needed-, is quite straightforward: modify the applying filter so that the updated rows are not filtered out.
headerFilter.setTableFilter( new TableFilter() { @Override public boolean include(Entry rowEntry) { return isModelRowChanged((Integer) rowEntry.getIdentifier()) || super.include(rowEntry); } });
It is needed here to program the isModelRowChanged method, returning true when the associated (model) row is changed.