14

Qt solution is a single call to resizeColumnsToContent(), in .NET one can use TextRenderer.MeasureText(), JTable could use AUTO_RESIZE_ALL_COLUMNS.

In SWT, is there a way to programmaticaly resize columns after populating them?

Calling computeSize(SWT.DEFAULT, SWT.DEFAULT) returns the same value thus disregarding character left overs in columns.
TableColumn has setWidth(), but how do I obtain the size hint for the current content taking into account font face, etc?

Peter Lang
  • 54,264
  • 27
  • 148
  • 161
MadH
  • 1,498
  • 4
  • 21
  • 29

2 Answers2

21

Solved with:

private static void resizeColumn(TableColumn tableColumn_)
{
    tableColumn_.pack();

}
private static void resizeTable(Table table_)
{
    for (TableColumn tc : table.getColumns())
        resizeColumn(tc);
}
MadH
  • 1,498
  • 4
  • 21
  • 29
  • 14
    Aren't one line functions rather useless? Why not just call pack in resizeTable? – Buttons840 Nov 04 '11 at 14:45
  • 1
    I agree with you in the above example, Buttons840. But they are not useless, if you want to make an unreadable 'one liner' more expressive/readable - so that the method name expresses better what you do. – Kai Mechel May 14 '14 at 08:59
4

In many cases, the table entries change at run-time to reflect changes in the data model. Adding entry to the data model requires to resize columns as well, but in my case calling .pack() after the modification of the model does not solved completly the problem. In particolar with decorations the last entry is never resized. This seams to be due to async table viewer update. This snipped solved my problem:

public class LabelDecoratorProvider extends DecoratingStyledCellLabelProvider {

    public LabelDecoratorProvider(IStyledLabelProvider labelProvider,  
        ILabelDecorator decorator, IDecorationContext decorationContext) {
        super(labelProvider, decorator, decorationContext);
    }

    @Override
    public void update(ViewerCell cell) {
        super.update(cell);
        if (TableViewer.class.isInstance(getViewer())) {
            TableViewer tableViewer = ((TableViewer)getViewer());
            Table table = tableViewer.getTable();
            for (int i = 0, n = table.getColumnCount(); i < n; i++)
                table.getColumn(i).pack();
        }
    }
}
nannimo
  • 56
  • 2