我在 Eclipse SWT 中有这个表,有 5 列。我调整了窗口的大小以及整个表格的大小,但列的大小没有调整以填充所有可用空间。
我可以使用一种布局方法来使列自行调整大小以填充所有可用空间吗?我发现一些代码可以在调整客户端空间大小时使列调整大小,但这对我来说似乎是一个小技巧。
肯定有一种通过使用布局本身来做到这一点的优雅方法。
这可能会派上用场:
Composite tableComposite = new Composite(parent, SWT.NONE);
TableViewer xslTable = new TableViewer(tableComposite, SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
xslTable.getTable().setLinesVisible(true);
xslTable.getTable().setHeaderVisible(true);
TableViewerColumn stylesheetColumn = new TableViewerColumn(xslTable, SWT.NONE);
stylesheetColumn.getColumn().setText(COLUMN_NAMES[0]);
stylesheetColumn.getColumn().setResizable(false);
TableViewerColumn conceptColumn = new TableViewerColumn(xslTable, SWT.NONE);
conceptColumn.getColumn().setText(COLUMN_NAMES[1]);
conceptColumn.getColumn().setResizable(false);
TableColumnLayout tableLayout = new TableColumnLayout();
tableComposite.setLayout(tableLayout);
layoutTableColumns();
layoutTableColumns
方法
/**
* Resize table columns so the concept column is packed and the stylesheet column takes the rest of the space
*/
private void layoutTableColumns()
{
// Resize the columns to fit the contents
conceptColumn.getColumn().pack();
stylesheetColumn.getColumn().pack();
// Use the packed widths as the minimum widths
int stylesheetWidth = stylesheetColumn.getColumn().getWidth();
int conceptWidth = conceptColumn.getColumn().getWidth();
// Set stylesheet column to fill 100% and concept column to fit 0%, but with their packed widths as minimums
tableLayout.setColumnData(stylesheetColumn.getColumn(), new ColumnWeightData(100, stylesheetWidth));
tableLayout.setColumnData(conceptColumn.getColumn(), new ColumnWeightData(0, conceptWidth));
}
这就是我尝试过的,效果很好。
viewer.getControl().addControlListener(new ControlListener() {
@Override
public void controlResized(ControlEvent arg0) {
Rectangle rect = viewer.getTable().getClientArea();
if(rect.width>0){
int extraSpace=rect.width/4;
col1.getColumn().setWidth(extraSpace);
col2.getColumn().setWidth(extraSpace);
col3.getColumn().setWidth(extraSpace);
col4.getColumn().setWidth(extraSpace);
}
}
@Override
public void controlMoved(ControlEvent arg0) {
// TODO Auto-generated method stub
}
});
我是这样解决的:
public static void makeLastColumnAutoExpand(Table table, int minWidth) {
var resizer = new ControlAdapter() {
@Override
public void controlResized(ControlEvent event) {
var columns = table.getColumns();
if (columns.length == 0)
return;
if (columns.length == 1) {
columns[0].setWidth(Math.max(minWidth, table.getClientArea().width));
return;
}
var totalWidthOfOtherColumns = 0;
for (var i = 0; i < columns.length - 1; i++) {
totalWidthOfOtherColumns += columns[i].getWidth();
}
var newWidth = Math.max(minWidth, table.getClientArea().width - totalWidthOfOtherColumns);
columns[columns.length - 1].setWidth(newWidth);
}
};
table.addControlListener(resizer);
for (final var col : table.getColumns()) {
col.addControlListener(resizer);
}
}
setLastColumnAutoExpand
向表格及其所有列添加 ControlListener
。这确保所有调整大小操作都会触发最后一列的自动调整大小。