Hide a column in JTable

Adesh singh picture Adesh singh · Dec 20, 2012 · Viewed 27.9k times · Source

Possible Duplicate:
How to make a columns in JTable Invisible for Swing Java
How to hide a particlar column in DefaultTableModel from displaying it in table?

I am trying to enter data to three columns in JTable, but I want to show only two columns. Actually, I want to hide the third column, not by setting the width to 0, but by any other method in which I can get the data from the hidden column on a click event.

How can I hide a column in this manner?

I am using the following code:

 try {
     String Title[]= new String{"a","b","c"};
     Object obj= new Object[50][3];
     JTable table= new JTable(obj,title);
     JScrollPane jsp= new JScrollPane(table); 
     add(jsp);
 } catch(Exception ex) {
     ex.printStackTrace();
 }

Answer

Amarnath picture Amarnath · Dec 20, 2012

Set the Column Minimum and Maximum width as zero.

table.getColumnModel().getColumn(columnIndex).setMinWidth(0);
table.getColumnModel().getColumn(columnIndex).setMaxWidth(0);

As link suggested by Andrew Thomson in the comment section you can also use removeColumn.

From javaDoc;

removeColumn

public void removeColumn(TableColumn aColumn) 

Removes aColumn from this JTable's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn that was responsible for displaying it. Parameters: aColumn - the TableColumn to be removed

P.S: But I have personally used the first approach to hide a column in the JTable. Thanks for removeColumn method I will try to use it from now on.