动态 ExpandItem 内容

public class ExpandBarDynamicContentExample {

    private final Display display;
    private final Shell shell;

    public ExpandBarDynamicContentExample() {
        display = new Display();
        shell = new Shell(display);
        shell.setLayout(new FillLayout());

        // Create the ExpandBar on the Shell
        final ExpandBar expandBar = new ExpandBar(shell, SWT.V_SCROLL);
        expandBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        // Add a single ExpandItem to the ExpandBar
        final ExpandItem expandItem = new ExpandItem(expandBar, SWT.NONE);
        expandItem.setText("ExpandItem");
        expandItem.setImage(new Image(display, "src/main/resources/sample.gif"));

        // Create a Composite which will hold all of the content in the ExpandItem
        final Composite expandContent = new Composite(expandBar, SWT.NONE);
        expandContent.setLayout(new GridLayout());

        // Add a button to add some dynamic content
        final Button button = new Button(expandContent, SWT.PUSH);
        button.setText("Add Label");
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                // Add another Label to the ExpandItem content
                new Label(expandContent, SWT.NONE).setText("Hello, World!");
                // Re-compute the size of the content
                expandItem.setHeight(expandContent.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
            }
        });

        // Set the Composite as the control for the ExpandItem
        expandItem.setControl(expandContent);
        // Set the height of the ExpandItem to be the computed size of its content
        expandItem.setHeight(expandContent.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
        expandItem.setExpanded(true);
    }

    public void run() {
        shell.setSize(200, 200);
        shell.open();

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

    public static void main(String... args) {
        new ExpandBarDynamicContentExample().run();
    }

}

结果是:

StackOverflow 文档

这里的关键区别是我们需要在内容更改后重新计算 ExpandItem 的大小。在 SelectionAdapter 中添加新的 Label 之后:

expandItem.setHeight(expandContent.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);

另请注意在 ExpandBar 构造函数中使用 SWT.V_SCROLL 样式位。这当然是可选的,但是添加它是为了确保在 Label 对象数量增加时可以访问所有内容。