How to make a columns in JTable Invisible for Swing Java

Solution 1:

Remove the TableColumn from the TableColumnModel.

TableColumnModel tcm = table.getColumnModel();
tcm.removeColumn( tcm.getColumn(...) );

If you need access to the data then you use table.getModel().getValueAt(...).

For a more complex solution that allows the user to hide/show columns as they wish check out the Table Column Manager.

Solution 2:

First remove the column from the view

 table.removeColumn(table.getColumnModel().getColumn(4));

Then retrieve the data from the model.

table.getModel().getValueAt(table.getSelectedRow(),4);

One thing to note is that when retrieving the data, it must be retrieve from model not from the table.

Solution 3:

I tried 2 possible solutions that both work, but got some issue with the 1st solution.

   table.removeColumn(table.getColumnModel().getColumn(4));

or

   table.getColumnModel().getColumn(4).setMinWidth(0);
   table.getColumnModel().getColumn(4).setMaxWidth(0);
   table.getColumnModel().getColumn(4).setWidth(0);

In my recent case, I preferred the 2nd solution because I added a TableRowSorter.

   TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
   table.setRowSorter(sorter);

When using table.removeColumn(table.getColumnModel().getColumn(4)), it will physically remove the column from the view/table so you cannot use table.getValueAt(row, 4) - it returns ArrayIndexOutOfBounds. The only way to get the value of the removed column is by calling table.getModel().getValueAt(table.getSelectedRow(),4). Since TableRowSorter sorts only what's on the table but not the data in the DefaultTableModel object, the problem is when you get the value after sorting the records - it will retrieve the data from DefaultModelObject, which is not sorted.

So I used the 2nd solution then used table.getValueAt(table.getSelectedRow(),4);

The only issue I see with the 2nd approach was mentioned by @camickr: "When you set the width to 0, try tabbing, when you hit the hidden column focus disappears until you tab again. This will confuse users."