JTable hide and show columns

I think you have named your methods incorrectly, when you want to hide a column you will set

column.setMinWidth(0);
column.setMaxWidth(0);
column.setPreferredWidth(0);

but in your code you are doing this when you want to show a column which is exactly opposite.

Also there is no need to call this "setWidth" method on a TableColumn, read TableColumn#setWidth(int).


instead of re-inventing the wheel you might consider to use JXTable (in the SwingX project) which supports hidden columns, comlete with a ui-control to allow users hiding/showing them dynamically - and a bunch of other useful thingies :).


JTable#removeColumn remove Column only from JTable view, more in this example


try this something like this for example:

myTableModel = new DefaultTableModel();
myTableModel.setColumnIdentifiers(new Object[]{"ID", "Name"});
JTable myTable = new JTable(myTableModel);

// remember to save the references
TableColumn myTableColumn0 = guiLoteryNumbersTable.getColumnModel().getColumn(0);
TableColumn myTableColumn1 = guiLoteryNumbersTable.getColumnModel().getColumn(1);
//...

// remove temporary the column ("hide")
myTable.getColumnModel().removeColumn(myTableColumn1);

// then you restore that column when you need it ("show")
myTable.getColumnModel().addColumn(myTableColumn1);

That's the best way I know to hide a column.

Tags:

Java

Swing

Jtable