Programmazione:Java/Eclipse RCP/Event Interface implementation

Da WikiSitech.
Vai alla navigazioneVai alla ricerca

How to implement Event Interface

This article use org.eclipse.swt.widgets.Listener interface as example....but it's valid for all interface

Bad Practice

public class TestEventImpl {

  Shell shell;
  Button bt;
  public void create() {
     shell = new Shell(PlatformUI.getWorkbench().getDisplay());
     
     Composite c = new Composite(shell, SWT.BORDER);
     bt = new Button(c, SWT.PUSH);
     bt.setText("Push ME");
     bt.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
           // Do something
        }
     });
     shell.addListener(SWT.Dispose, new Listener() {
        public void handleEvent(Event event) {
           // I can't remove listener...I don't have reference....
        }
     });
     shell.open();
  }

}

Not Bad Practice but...

public class TestEventImpl {

  Listener bt_listener, shell_listener;
  Shell shell;
  Button bt;
  public void create() {
     shell = new Shell(PlatformUI.getWorkbench().getDisplay());
     
     Composite c = new Composite(shell, SWT.BORDER);
     bt = new Button(c, SWT.PUSH);
     bt.setText("Push ME");
     bt_listener = new Listener() {
        public void handleEvent(Event event) {
           // Do something
        }
     }
     bt.addListener(SWT.Selection, bt_listener);
     shell_listener = new Listener() {
        public void handleEvent(Event event) {
           TestEventImpl parent = (TestEventImpl)event.widget.getData("ClassParent");
           parent.bt.removeListener(bt_listener);
           parent.shell.removeListener(shell_listener);
        }
     }
     shell.addListener(SWT.Dispose, shell_listener);
     shell.setData("ClassParent", this); // must save a class reference
     shell.open();
  }

}

Best Practice

public class TestEventImpl implements Listener {

  Shell shell;
  Button bt;
  public void create() {
     shell = new Shell(PlatformUI.getWorkbench().getDisplay());
     Composite c = new Composite(shell, SWT.BORDER);
     bt = new Button(c, SWT.PUSH);
     bt.setText("Push ME");
     bt.addListener(SWT.Selection, this);
     shell.addListener(SWT.Dispose, this);
     shell.open();
  }
  public void handleEvent(Event event) {
     switch(event.type) {
        case SWT.Selection: 
           if(event.widget == bt) {
              // Do something
           }
        break;
        case SWT.Dispose: 
           if(event.widget == shell) {
              bt.removeListener(this);
              shell.removeListener(this);
           }
        break;
     }
  }

}