Is there any implementation in place in Java to filter a JTable (using a search JTextField) by its column (header value) rather than its row? I need columns to show/hide according to the string found when searching.
3 Answers
Is there any implementation in place in Java to filter a JTable (using a search JTextField) by its column (header value) rather than its row?
- yes have look at RowFilter and apply to required column
I need columns to show/hide according to the string found when searching.
not an easy job, because it requires a lot of effort, and excellent knowledge about
Java Essential classes
,Swing
and being an expert withJTable
I wouldn't go this way, use proper
ColumnRender
, then Column should be highlighted, instead of jumping (hide --> show ---> hide etc.) ofJTables Column
on the screenthere are some examples about
RowFilter
,RowSorter
, never needed that, never tried.

- 21,642
- 4
- 51
- 73

- 109,525
- 20
- 134
- 319
-
See also this [Q&A](http://stackoverflow.com/q/7137786/230513) on responding to table header clicks. – trashgod Oct 10 '12 at 01:55
You could use a custom TableModel implementation that wraps your real model to do the filtering. Just keep notifying the TableModelListeners whenever the columns change.

- 22,200
- 14
- 65
- 81
I think I've got it working like this:
Declare some global variable for a temporary table and table model to hold the hidden columns:
private JTable hiddenTable = new JTable();
private DefaultTableColumnModel hiddenModel = new DefaultTableColumnModel();
Then use a filter method for every key pressed to add the columns to hide to the temporary table model while removing them from the main table model. You then show them again when the string matches by adding them back to the main table, and removing them from the temporary one:
private void filterList() {
// Hide columns
for (TableColumn column : table.getColumns()) {
if (!((String) column.getHeaderValue()).toLowerCase().contains(
searchBox.getText().toLowerCase().trim())) {
hiddenModel.addColumn(column);
table.getColumnModel().removeColumn(column);
}
}
// Show columns
for (TableColumn column : hiddenTable.getColumns()) {
if (((String) column.getHeaderValue()).toLowerCase().contains(
searchBox.getText().toLowerCase().trim())) {
table.getColumnModel().addColumn(column);
hiddenModel.removeColumn(column);
}
}
}
The only problem here is that the columns lose their order when added back into the table.

- 188
- 3
- 5
- 12