Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable hide and show columns

Tags:

java

swing

jtable

I want to add some columns to a table (Swing JTable). Some of them will have a default size (e.g. 250), others will be hidden (so their size will be 0). I use this code:

 model = new DefaultTableModel();
 table = new JTable(model);
 setAutoResizeMode(AUTO_RESIZE_OFF);
 for (int i = 1; i < COLUMN_NAMES.length; i++) {
    model.addColumn(COLUMN_NAMES[i]);
    if (show[i]) show(index);
    else hide(index);
 }
 ........

 private void hide(int index) {
    TableColumn column = getColumnModel().getColumn(index);
    column.setMinWidth(0);
    column.setMaxWidth(0);
    column.setWidth(0);
    column.setPreferredWidth(0);
    doLayout();
}

private void show(int index) {
    final int width = 250;
    column.setMinWidth(15);
    column.setMaxWidth(width);
    column.setWidth(width);
    column.setPreferredWidth(width);
    doLayout();
}

the problem is when the table is displayed, all the columns are showed (none is hidden) and their size is not 250 but they have all the same size.

How can I get the wanted effect?

like image 892
Randomize Avatar asked Dec 03 '11 21:12

Randomize


1 Answers

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

like image 194
mKorbel Avatar answered Oct 01 '22 20:10

mKorbel