26

I need to hide a composite (and all children inside). Just setting setVisible(false) will keep the space of the composite.

Composite outer = new Composite(parent, SWT.NONE);      
outer.setLayout(new GridLayout(1,false));
outer.setLayoutData(new GridData(GridData.FILL_BOTH) );

Composite compToHide = new MyComposite(outer, SWT.NONE);        
compToHide.setLayout(new GridLayout());
compToHide.setVisible(false);
Lii
  • 11,553
  • 8
  • 64
  • 88
yuris
  • 1,109
  • 4
  • 19
  • 33
  • Solution is similar to http://stackoverflow.com/questions/17511442/eclipse-plugin-make-combo-to-handle-enter-key i.e. addListener() – Paul Verest Jul 08 '13 at 08:11

2 Answers2

32

Here is some code that does what you want. I basically use GridData#exclude in combination with Control#setVisible(boolean) to hide/unhide the Composite:

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

    Button hideButton = new Button(shell, SWT.PUSH);
    hideButton.setText("Toggle");

    final Composite content = new Composite(shell, SWT.NONE);
    content.setLayout(new GridLayout(3, false));

    final GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
    content.setLayoutData(data);

    for(int i = 0; i < 10; i++)
    {
        new Label(content, SWT.NONE).setText("Label " + i);
    }

    hideButton.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            data.exclude = !data.exclude;
            content.setVisible(!data.exclude);
            content.getParent().pack();
        }
    });

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

Before hiding:

enter image description here

After hiding:

enter image description here

Baz
  • 36,440
  • 11
  • 68
  • 94
  • 1
    the problem is with shell.pack(), I can't use it because it affects whole gui – yuris Jul 07 '13 at 15:54
  • @yuris Can you use `pack()` on the parent of the composite you are trying to hide? If so, look at my updated code. If not, you will have to manually decrease the size of the shell by the size of the hidden composite. – Baz Jul 07 '13 at 16:11
  • 4
    How about `content.getParent().layout(true, true)`? – winklerrr Aug 03 '16 at 12:18
5

Define a GridData for your control and then after you do: control.setVisible(false) do gridData.exclude=true

ACV
  • 9,964
  • 5
  • 76
  • 81