Oct 11, 2007

Removing Widgets from a composite

One of the frequent questions from Swing-to-SWT developers is: What is the equivalent of the Container.remove method in SWT?

AFAIK, there is none. The Composite doesn't have any method to remove its children. But then we have a workaround. We can dispose the child widget!

Let me give a simple code to explain. The problem statement is simple: Have a Combo box for different UI elements and fill a composite based on the selection. Hope the code is clear and doesn't require any clarifications.

composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));

Label label = new Label(composite, SWT.None);
label.setText("Select Control:");

combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
combo.add("Text Box");
combo.add("Combo");
combo.add("Radio Button");

combo.addSelectionListener(new SelectionAdapter() {

@Override
public void widgetSelected(SelectionEvent e) {

if (control != null)
control.dispose();


switch (combo.getSelectionIndex()) {
case 0:
control = new Text(composite, SWT.BORDER);
break;
case 1:
control = new Combo(composite, SWT.DROP_DOWN);
break;
case 2:
control = new Button(composite, SWT.RADIO);
break;
}

GridData data = new GridData(SWT.FILL, SWT.NONE, false, false);
data.horizontalSpan = 2;
control.setLayoutData(data);

composite.layout(true);
}
});

Here is the result:





2 comments:

Benjamin Cabé said...

Have a look at http://www.jroller.com/eu/entry/swt_stacklayout ! :)

Pranni said...

Yup, saw that. That was quick :-)