Java - Table 不会调整大小

Java - Table won't resize

你好,我是 java 的初学者,我对 table 的尺码有疑问。

上first picture you can see the sizing is very good, but when I click on the button the size of the table will shrink picture two).

感谢您的帮助:)

protected void createContents() {

    ...

    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.horizontalSpan = 2;
    gridData.grabExcessHorizontalSpace = true;

    table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
    table.setLayoutData(gridData);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);

    TableColumn columnProduct = new TableColumn(table, SWT.NONE);
    columnProduct.setText("Product");
    TableColumn columnKey = new TableColumn(table, SWT.NONE);
    columnKey.setText("Key");

    for (int i = 0; i < 2; i++)
    {
        table.getColumn(i).pack();
    }

    shell.pack();
    shell.open();
}

@Override
public void mouseDown(MouseEvent e) {
    TableItem tItem = new TableItem(table, SWT.FILL);
    String[] data = { txtProduct.getText(), txtKey.getText()};
    tItem.setText(data);
    table.pack();
}

如果您希望列根据内容自动调整大小,请在列上使用 pack(),而不是 table:

for (TableColumn column : table.getColumns()) {
    column.pack();
}

如果您希望 table 使用额外的垂直 space 然后相应地设置它的 gridData:

...
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;

// add these:
gridData.verticalAlignment = SWT.FILL;
gridData.grabExcessVerticalSpace = true;