動態 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 物件數量增加時可以訪問所有內容。