alhcr
alhcr

Reputation: 823

How to replace content of grid cell in SWT GridLayout?

I need to replace content of grid cell after button click. For example: there is Label and I need to replace it with Text. Is it possible with GridLayout? I need to use SWT.

Upvotes: 6

Views: 4673

Answers (1)

Edward Thomson
Edward Thomson

Reputation: 78703

You can simply dispose the Label and put a new Text in its place. GridLayout uses the z-order of children to determine the location in the grid, so you'll need to use the moveAbove() and moveBelow() on the Text in order to get it in the correct location. Then call layout() on the parent. For example:

Text text = new Text(label.getParent(), SWT.BORDER);
text.moveAbove(label);
label.dispose();
text.getParent().layout();

Here's a simple widget that illustrates exactly what I mean:

public class ReplaceWidgetComposite
    extends Composite
{
    private Label label;
    private Text text;
    private Button button;

    public ReplaceWidgetComposite(Composite parent, int style)
    {
        super(parent, style);

        setLayout(new GridLayout(1, false));

        label = new Label(this, SWT.NONE);
        label.setText("This is a label!");

        button = new Button(this, SWT.PUSH);
        button.setText("Press me to change");
        button.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                text = new Text(ReplaceWidgetComposite.this, SWT.BORDER);
                text.setText("Now it's a text!");
                text.moveAbove(label);
                label.dispose();
                button.dispose();
                ReplaceWidgetComposite.this.layout(true);
            }
        });
    }
}

Upvotes: 9

Related Questions