Java Swing: Trying to hide and show JTable’s column doesn’t work with dynamic width

I am trying to create a JTable that would have a dynamic width (according to the largest element in the column) and I am using this code

JTable table = new JTable(){
    @Override
       public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
           Component component = super.prepareRenderer(renderer, row, column);
           int rendererWidth = component.getPreferredSize().width;
           TableColumn tableColumn = getColumnModel().getColumn(column);
           tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
           return component;
        }
    };
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

The dynamic width is working correctly, but then I have an event listener to chechboxes (1 chechbox = 1 column) and if they are unticked, the column should be hidden, if they are ticked again, the column should re-apear. For that I am using:

if (jCheckBox.isSelected())
{
    table.getColumn(columnName).setMinWidth(15);
    table.getColumn(columnName).setMaxWidth(2147483647);
    table.getColumn(columnName).setWidth(100);
}
else
{
    table.getColumn(columnName).setMinWidth(0);
    table.getColumn(columnName).setMaxWidth(0);
    table.getColumn(columnName).setWidth(0);
}

And this piece of code was working perfectly, but I think this line:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

breaks the functionality, now, hiding the column works, but re-appearing does not. Do you know what could be the problem? Thanks!

Answer

change

table.getColumn(columnName).setWidth(0);

to

table.getColumn(columnName).setPreferredWidth(0);

Leave a Reply

Your email address will not be published. Required fields are marked *