如何使用 GridLayout 将 table 高度调整为 SWT 中的项目数?

How to adjust the table height to the number of items in SWT with GridLayout?

我想要一个 table 高度完全根据项目数量调整的。我正在使用 SWT,我正在使用 GridLayout。这是我的代码的摘录:

Table table = new Table(parent, SWT.BORDER);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tc1 = new TableColumn(table, SWT.CENTER);
TableColumn tc2 = new TableColumn(table, SWT.CENTER);
tc1.setText("Column1");
tc2.setText("Column2");
tc1.setWidth(85);
tc2.setWidth(90);

for (int i = 0; i < 3; i++) {
    TableItem item = new TableItem(table, SWT.NONE);
    item.setText(0, "Text Column1");
    item.setText(1, "Text Column2");
}

GridData gridData = new GridData(tc1.getWidth()+tc2.getWidth()-17, ???);
table.setLayoutData(gridData);

对于宽度我找到了一个公式。但是为了身高?

使用Table::getItemHeight()计算给定数量的项目所需的客户身高。然后使用 computeTrim() 计算给定客户端高度的边界。如果显示网格线,则添加每条分隔线的宽度。最后,可以用GridDataheightHint建议GridLayout为table预留一定的高度。

例如:

int clientWidth = ...
int clientHeight = table.getItemHeight * numberOfItems;
if( table.getLinesVisible() && numberOfItems > 0 ) {
  clientHeight += table.getGridLineWidth() * ( numberOfItems - 1 );
}
Rectangle bounds = table.computeTrim( 0, 0, clientWidth, clientHeight );

GridData gridData = new GridData( SWT.DEFAULT, clientHeight );

如果您的客户端宽度是在别处计算的,您也可以将其设置为零。