I have created JTable with fixed no of rows and columns.Then depending upon some conditions I want to hide one column,but the methods removeColumn or setting maxWidth to 0 are not working.I am not getting any error.
How can I do this?

8 Years
Discussion Span
Last Post by BestJewSinceJC

hi, i spend many sleeples nights trying to solve it i did it this way:
first create custom table model like this, and ascribe it to the table:

DefaultTableModel tableModel  = new DefaultTableModel(null,new String[]{"Column1", "Column2", "Column3"});

then to remove column from view you do


where columnId is column number from table model
to bring it back

table.addColumn(new TableColumn(columnId));

you have to remember about:

  • repaint() each time you add, remove column
  • always remove columns from the last one, because if you have columns 0,1,2,3 and remove column(0) the indexes are recount and you will have columns 0,1,2
  • use

    first if you want to read data

  • add, change, remove rows should be done on tableModel, not on the table directly

i guess there is many ways to do this, but i found only this one to work
its get a little bit more tricky if you want to sort the table too...


I think you have to call the revalidate method on your JTable, after removing or adding a column, to make it work. Its been a while, but I think that's the advice Ezzaral gave me when I asked a similar question before (I could be misquoting him; whatever advice he gave me worked).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.