首页 > 解决方案 > 如何在不提供静态列宽的情况下创建具有多列的 Java SWT 表

问题描述

我目前正在开发一个 Eclipse 插件,在该插件中,有一个表单视图作为设计模板。在该表单视图中,我添加了一个表格,并且应该有两列的宽度比为 1:2。而且我还希望该表能够响应并动态更改其列宽以适应 formView 页面宽度。

以下代码段是我目前正在使用的代码段。

        Table table = new Table(parent, SWT.MULTI | SWT.H_SCROLL | SWT.BORDER);
        fd = new FormData();
        fd.height = 200;
        fd.top = new FormAttachment(removeTestCaseButton, 5);
        fd.left = new FormAttachment(1);
        fd.right = new FormAttachment(99);
        table.setLayoutData(fd);
        table.setLinesVisible(true);
        table.setHeaderVisible(true);

        TableColumn column1 = new TableColumn(testCaseTable, SWT.CENTER);
        column.setText("column One");

        TableColumn column2 = new TableColumn(testCaseTable, SWT.CENTER);
        column2.setText("column Two");

        form.addControlListener(new ControlAdapter() {
            public void controlResized(ControlEvent e) {
                Rectangle area = form.getBody().getClientArea();
                int width = area.width;         
                column1.setWidth(width / 3);
                column1.setWidth(width * 2 / 3);
            }
        });

但是这里的问题是当我打开 FormView 时它工作正常。但是我的桌子在Section里面。一旦我展开或折叠部分,表格宽度就会随着水平滚动条的出现而增加。

我只想要一个可靠的解决方案。

标签: javaeclipseeclipse-pluginswt

解决方案


TableViewer使用带有TableColumnLayoutand的 JFace 更容易做到这一点ColumnWeightData,但是您必须重新编写代码以使用 JFace 样式的内容和表格的标签提供程序。

TableColumnLayout tableLayout = new TableColumnLayout();

// A separate composite containing just the table viewer is required
Composite tableComp = new Composite(parent, SWT.NONE);

tableComp.setLayout(tableLayout);

TableViewer viewer = new TableViewer(tableComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);

TableViewerColumn col1 = new TableViewerColumn(viewer, SWT.LEAD);
col1.getColumn().setText("Column 1");

col1.setLabelProvider(.... label provider for column 1 ....);

// Weight for column
tableLayout.setColumnData(col1.getColumn(), new ColumnWeightData(60));

TableViewerColumn col2 = new TableViewerColumn(viewer, SWT.LEAD);
col2.getColumn().setText("Column 2");

col2.setLabelProvider(....... label provider for column 2 .....);

// Weight for column
tableLayout.setColumnData(col2.getColumn(), new ColumnWeightData(40));

viewer.getTable().setHeaderVisible(true);
viewer.getTable().setLinesVisible(true);

viewer.setContentProvider(ArrayContentProvider.getInstance());

viewer.setInput(.... input data for the viewer ....);

推荐阅读