Search code examples
javauser-interfaceeclipse-rcpe4

Get GUI components of Eclipse E4


We constructed a GUI with Eclipse E4. Now we need to connect to the GUI from a non GUi class. How can we connect to a label in a Tool Control or how can we connect to all the GUI components in Eclipse E4?

We already looked at the @inject but without any success.

The Gui of our application looks like this: enter image description here


Solution

  • One way to do this is to use a manager object which provides methods to set the control's value. You put the manager object in the Eclipse context so that it can be injected in to any class (provided the class is created by the injection system).

    You can create a manager class in the Eclipse context in several ways, one is just to declare as:

    @Creatable
    @Singleton
    public class MyMananger
    

    which will cause the injection system to create a single instance of the class used wherever it is injected. You can also use an OSGi service, a ContextFunction or directly set an object in to the IEclipseContext (perhaps in the LifeCycle class).

    Your Tool Control code can inject the manager and tell it about the control it should update.

    Other code wishing to update the control can inject the manager and call methods to set the control's value.

    As I mentioned only code which is created by the injection system can use @Inject. If you are create a class using new you are not using the injection system. Use the ContextInjectionFactory.make method instead.

    Here is a very simple 'status line' code adapted from code I use:

    The manager:

    @Creatable
    @Singleton
    public final class StatusLineManager
    {
      /** Label control to show the status */
      private Label _label;
    
      public StatusLineManager()
      {
      }
    
      void setLabel(Label label)
      {
        _label = label;
      }
    
      public void setText(String text)
      {
        if (_label != null && !_label.isDisposed())
          _label.setText(text);
      }
    }
    

    The status line Tool Control:

    public class StatusLineControl
    {
      public StatusLineControl()
      {
      }
    
      @PostConstruct
      public void postConstruct(Composite parent, StatusLineManager manager)
      {
        Composite body = new Composite(parent, SWT.NONE);
    
        body.setLayout(GridLayoutFactory.fillDefaults().extendedMargins(10, 0, 4, 0).create());
    
        Label label = new Label(body, SWT.NONE);
    
        label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
    
        // Tell the manager about the label
    
        manager.setLabel(label);
      }
    }