How to ... / FAQs
- How to create a table filter
- Listening for sorting events
- Create additional user filters
- Remove the table filter header
- How to create a table filter
The tutorial 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); } });
- Remove the table filter header
If the filter header has been including in the GUI automatically -as it happens when is associated to a table, and the Position is INLINE or TOP-, to remove the filter header from the GUI it is enough to invoke again setTable, passing a null parameter:
filterHeader.setTable(null);
If the filter header has been included manually in the GUI -using the NONE position-, in addition to the previous call is obviously needed to manually exclude the header from the GUI.