swtjface

Let a Composite in a GridLayout take as much space as its children need


What I’m trying to accomplish is a Composite with another two Composites within. The first Composite should be a scrollable menu. In addition to that, I want it to take as much space as its children need without providing any absolute sizes. The other Composite contains the main content and should take all the remaining space.

Right now my example code does not show a scrollbar and that is because I don’t call setMinSize() on it. However, I don’t know how to calculate setMinSize(), because the inner Composite uses the same sizes as the ScrollableComposite and cuts some of its content off.

I guess the question is, is it possible to use a GridLayout to use as much space as needed while its parent depends on the child’s actual sizes.

Here's my code:

Composite composite = new Composite(shell, SWT.NONE);
composite.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_YELLOW));
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);

ScrolledComposite scrolledComposite = new ScrolledComposite(composite, SWT.H_SCROLL |
        SWT.V_SCROLL);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
// scrolledComposite.setMinSize(SWT.DEFAULT, 200);
GridDataFactory.fillDefaults().grab(false, true).applyTo(scrolledComposite);

Composite composite1 = new Composite(scrolledComposite, SWT.NONE);
scrolledComposite.setContent(composite1);
composite1.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLUE));
GridLayoutFactory.fillDefaults().numColumns(1).applyTo(composite1);

Button button11 = new Button(composite1, SWT.PUSH);
button11.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GREEN));
button11.setText("One One One One One");
GridDataFactory.fillDefaults().applyTo(button11);

for (int i = 0; i < 10; ++i) {
    Button button12 = new Button(composite1, SWT.PUSH);
    button12.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GREEN));
    button12.setText("One Two");
    GridDataFactory.fillDefaults().applyTo(button12);
}

Composite composite2 = new Composite(composite, SWT.NONE);
composite2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_RED));
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite2);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite2);

Button button2 = new Button(composite2, SWT.PUSH);
button2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GREEN));
button2.setText("Two");
GridDataFactory.fillDefaults().applyTo(button2);

Solution

  • Use

    scrolledComposite.setMinSize(composite1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
    

    After adding everything to composite1 to set the scrolled composite min size to the size computed for the composite (so put this after the for loop).