Hi!!
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?

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

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

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
    table.convertColumnIndexToModel(table.getSelectedRow());

    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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.