5

I want Layout in SWT which acts like cardLayout of Swing. My Main requirement is like I have a checkBox and have 2 SWT groups.

And based on checkbox selection and deselection need to show the SWT groups respectively in the same position.

Precisely only one group must be visible at a time based in checkbox state. How to achieve the same.

Baz
  • 36,440
  • 11
  • 68
  • 94
Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128

1 Answers1

8

You can use a StackLayout to achieve what you want:

private static boolean buttonOnTop = true;

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("StackOverflow");

    shell.setLayout(new FillLayout());

    Button switchButton = new Button(shell, SWT.NONE);
    switchButton.setText("Switch");

    final StackLayout layout = new StackLayout();

    final Composite content = new Composite(shell, SWT.NONE);
    content.setLayout(layout);

    final Button button = new Button(content, SWT.PUSH);
    button.setText("Button");

    final Label label = new Label(content, SWT.NONE);
    label.setText("Label");

    layout.topControl = button;

    switchButton.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            layout.topControl = (buttonOnTop) ? label : button;
            content.layout();

            buttonOnTop = !buttonOnTop;
        }
    });

    shell.pack();
    shell.open();

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

By setting StackLayout#topControl you can "move" your Control to the top.

Baz
  • 36,440
  • 11
  • 68
  • 94
  • Is there a way to make the layout switch between showing something and not, and reducing its size to zero when it's showing nothing. I'm trying to use StackLayout to make the Composite show or hide a child composite, by switching between that composite and an empty Composite. But when the empty Composite is showing, it still takes up the same space as the other control. – MidnightJava Oct 27 '15 at 21:09
  • @MidnightJava Did you try [this](http://stackoverflow.com/questions/17513210/how-to-hide-swt-composite-so-that-it-takes-no-space)? – Baz Oct 27 '15 at 21:11
  • Apparently this is a feature, not a problem. StackLayout makes all the underlying controls the same size. I got the effect I wanted by setting visible false on the Composite and exclude true on the Composite's GridData. I did what''s described in this post: http://stackoverflow.com/questions/17513210/how-to-hide-swt-composite-so-that-it-takes-no-space – MidnightJava Oct 27 '15 at 22:01
  • Thanks Baz! I saw after posting my comment that you had pointed me to the same link. – MidnightJava Oct 27 '15 at 22:03