SWT/JFace: remove widgets
Asked Answered
P

4

13
Group group = new Group(parent, SWT.NONE);
StyledText comment = new StyledText(group, SWT.BORDER_DASH);

This creates a group with a text area inside.

How can I later delete the text (remove it from the screen so that I can replace it with something else)?

Pendentive answered 1/4, 2009 at 7:55 Comment(0)
G
8

Use Widget.dispose.

public class DisposeDemo {
  private static void addControls(final Shell shell) {
    shell.setLayout(new GridLayout());
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Click to remove all controls from shell");
    button.addSelectionListener(new SelectionListener() {
      @Override public void widgetDefaultSelected(SelectionEvent event) {}
      @Override public void widgetSelected(SelectionEvent event) {
        for (Control kid : shell.getChildren()) {
          kid.dispose();
        }
      }
    });
    for (int i = 0; i < 5; i++) {
      Label label = new Label(shell, SWT.NONE);
      label.setText("Hello, World!");
    }
    shell.pack();
  }

  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    addControls(shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}
Granulate answered 1/4, 2009 at 9:56 Comment(0)
E
2

Another option is to use a StackLayout to switch between underlying controls. This prevents you from running into a "widget is disposed" error.

Elmaelmajian answered 17/4, 2009 at 18:35 Comment(0)
A
1

You have to either call comment.changeParent(newParent) or comment.setVisible(false) to remove/hide it from the Group. I am unsure if comment.changeParent(null) would work but I would give that a try.

We do it this way because SWT uses the Composite Pattern.

Abstractionism answered 1/4, 2009 at 8:35 Comment(0)
P
1

group.getChildren()[0].dispose() will remove the first child. You need to find a way to identify the precise child you want to delete. It could be comparing the id. You can do that by using the setData / getData on that control:

For example:

StyledText comment = new StyledText(group, SWT.BORDER_DASH);
comment.setData("ID","commentEditBox");

and then:

for (Control ctrl : group.getChildren()) {
 if (control.getData("ID").equals("commentEditBox")) {
   ctrl.dispose();
   break;
 }
}
Paratuberculosis answered 22/11, 2017 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.