如何正确避免SWT table 放大?

How to avoid SWT table enlargement correctly?

我有一个像这样的简单 SWT 程序:

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));
    shell.setMinimumSize(300, 300);

    // table
    final Table table = new Table(shell, SWT.BORDER);
    final GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
    gridData.heightHint = 0; // "hack"
    table.setLayoutData(gridData);

    // example data
    for (int i = 0; i < 50; i++) {
        final TableItem item = new TableItem(table, SWT.NONE);
        item.setText("item no." + i);
    }

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

我的期望 - 我希望 table 完全填满 shells space 而不改变它的大小。 (屏幕截图 1 和 3)

问题 - 如果我向 table 添加行,table 会自动调整大小(shell 也会自动调整大小)。 (截图 2)

解决方法 - 为了避免这种行为,我在代码中添加了行 gridData.heightHint = 0;。但这对我来说似乎是一个黑客。

问题 - 添加数据时避免扩大table(和shell)的正确方法是什么?

问候,winklerrr

截图 1

没有数据,table 和 shell 两个版本都不会调整大小,行为正确

截图 2

根据数据,table 和 shell 被放大,错误行为,只有 没有黑客攻击

截图 3

有了数据,table 和 shell 没有调整大小,添加了滚动条,正确的行为,只有 hack

在将数据添加到 table?

之前的某个时刻调用 shell.setSize(int width, int height)

您通常期望 table 具有特定的 逻辑 高度,比如 20 行。至少这是我经常选择的方法。

为了实现这一点,我像这样计算预期的初始高度(以像素为单位)并将其用作高度提示。

gridData.heightHint = table.getItemHeight() * 20;

为了更准确,您还需要添加 table 的 trim。

shell.setSize(int width, int height)

将此代码添加到您的 table 数据后。