Pergunta

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.

Foi útil?

Solução 3

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.

Outras dicas

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 with JTable

  • I wouldn't go this way, use proper ColumnRender, then Column should be highlighted, instead of jumping (hide --> show ---> hide etc.) of JTables Column on the screen

  • there are some examples about RowFilter, RowSorter, never needed that, never tried.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top