gpt4 book ai didi

java - 设置SWT表列的宽度

转载 作者:行者123 更新时间:2023-12-01 15:05:06 25 4
gpt4 key购买 nike

我正在将列一一添加到我的 swt 表中。与

int totalwidth=0;
for(String s:phoneErrs){
TableColumn tblclmnError = new TableColumn(tablephone, SWT.CENTER);
tblclmnError.setText(s);
tblclmnError.pack();
totalwidth+=tblclmnError.getWidth();
}

在此之后我想添加最后一列,它应该填充其余的内容表头中的空格。现在我有了添加列的总宽度已经,我应该能够计算最后一列的宽度并指定对的?但如何呢?我试过了

TableColumn tblclmnComment = new TableColumn(tablephone, SWT.CENTER);
tblclmnComment.setWidth(tablephone.getSize().x-totalwidth);
tblclmnComment.setText("Comment");

但它不起作用。 getSize() 返回 0

最佳答案

您可以通过在 SWT.Resize 事件类型上添加监听器来实现此目的。

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

TableViewer viewer1 = getViewer(shell);

List<String> rows = new ArrayList<String>();
rows.add("Row 1");
rows.add("Row 2");

viewer1.setInput(rows);

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

private static TableViewer getViewer(final Shell shell) {
TableViewer viewer = new TableViewer(shell, SWT.FULL_SELECTION
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.NONE);

viewer.getTable().addListener(SWT.Resize, new Listener() {

@Override
public void handleEvent(Event event) {


Table table = (Table)event.widget;
int columnCount = table.getColumnCount();
if(columnCount == 0)
return;
Rectangle area = table.getClientArea();
int totalAreaWdith = area.width;
int lineWidth = table.getGridLineWidth();
int totalGridLineWidth = (columnCount-1)*lineWidth;
int totalColumnWidth = 0;
for(TableColumn column: table.getColumns())
{
totalColumnWidth = totalColumnWidth+column.getWidth();
}
int diff = totalAreaWdith-(totalColumnWidth+totalGridLineWidth);

TableColumn lastCol = table.getColumns()[columnCount-1];

//check diff is valid or not. setting negetive width doesnt make sense.
lastCol.setWidth(diff+lastCol.getWidth());

}
});

viewer.setContentProvider(ArrayContentProvider.getInstance());

viewer.getTable().setLayoutData(
new GridData(SWT.FILL, SWT.FILL, true, true));

TableViewerColumn col = new TableViewerColumn(viewer, SWT.NONE);
col.getColumn().setWidth(100);
col.getColumn().setText("Text Column");
col.setLabelProvider(new ColumnLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText((String) cell.getElement());
}
});

col = new TableViewerColumn(viewer, SWT.NONE);
col.getColumn().setWidth(100);
col.getColumn().setText("Second Text Column");
col.setLabelProvider(new ColumnLabelProvider() {
@Override
public void update(ViewerCell cell) {
cell.setText((String) cell.getElement());
}
});


viewer.getTable().setHeaderVisible(true);

return viewer;
}

关于java - 设置SWT表列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13073487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com