Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWT/JFace: remove widgets

Tags:

java

swt

jface

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)?

like image 805
Thilo Avatar asked Apr 01 '09 07:04

Thilo


3 Answers

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();
  }
}
like image 71
McDowell Avatar answered Nov 16 '22 03:11

McDowell


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

like image 28
James Van Huis Avatar answered Nov 16 '22 03:11

James Van Huis


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.

like image 41
daanish.rumani Avatar answered Nov 16 '22 02:11

daanish.rumani