javajtableswingxtablecolumnjxtable

Preventing JXTable from automatically adjusting column widths


There's a specific scenario I've run into with JXTable (maybe its even a JTable issue) regarding what happens AFTER I execute a 'Pack All Columns' call.

'Pack All Columns' works fine, but when I then manually make a column width smaller, upon the next TableModelEvent received, the column width I modified is then always made LARGER. I notice that JTable's private setWidthsFromPreferredWidths() is ultimately called which looks like the culprit.

Again, this issue only occurs after I select 'Pack All Columns'. Is this a known bug or is this the intended behavior of 'Pack All Columns'?


Solution

  • I actually found an answer to my question at http://www.coderanch.com/

    It involved overriding the columnMarginChanged(ChangeEvent) method to ensure the getWidth() and getPreferredWidth() of a column were in sync:

    @Override
    public void columnMarginChanged(final ChangeEvent e)
    {
        super.columnMarginChanged(e);
    
        if (isEditing())
        {
            removeEditor();
        }
        TableColumn resizingColumn = null;
        if (tableHeader != null)
        {
            resizingColumn = tableHeader.getResizingColumn();
        }
        if (resizingColumn != null)
        {
            if (autoResizeMode == AUTO_RESIZE_OFF)
            {
                resizingColumn.setPreferredWidth(resizingColumn.getWidth());
            }
            else
            { 
                SwingUtilities.invokeLater(new Runnable()
                {
    
                    @Override
                    public void run()
                    {
                        doLayout();
                        repaint();
                    }
                });
            }
        }
        else
        {
            resizeAndRepaint();
        }
    }