Search code examples
jtablejpaneldynamic-resizing

Align JPanels with JTable columns


I've created an additional header consisting of JPanels for a JTable. Each JPanel should be as wide as the corresponding column of the JTable below. This works if widths are fixed. However, I want the JTables columns to be resizeable with the JPanels widths being adjusted on the fly. I can't get this to work. My current approach is to extend the DefaultTableColumnModel overriding fireColumnMarginChanged method:

private class MyTableColumnModel extends DefaultTableColumnModel{
    @Override
    protected void fireColumnMarginChanged(){
        header.setWidth(table.getSelectedColumn(),table.getSelectedColumn()).getWidth());               
        super.fireColumnMarginChanged();
    }
}

The "header" has got a method setWidth(int column, int width). But there are several problems with this approach:

fireColumnMarginChanged is fired all the time while changing a columns width, instead of just being fired once, when the final width is set

table.getSelectedColumn does not return the column being resized, but rather the one being clicked on last

I'd like to know if there is an easier way to do the resizing on the fly or if my approach is not hopeless and can be fixed somehow. I'd appreciate any hints I can get.


Solution

  • Finally, I came up with a solution:

    • Create a method to adjust sizes in the Table class: This method retrieves the width of each table column, and sets each panels width respectively.
    • Add a component Listener to the Table class and call that method on componentResized.

    That's it.