Saturday, April 2, 2016

Reacting to UI events in Eclipse E4

Approach 1 - Using dependency injection together with the @UIEventTopic annotation

  • The @UIEventTopic ensures the event notification is performed in the user interface thread.
  •  The method gets executed each time the part is clicked on.

package com.example;

import javax.inject.Inject;

import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.osgi.service.event.Event;

public class StatusPart {

    @Inject
    @Optional
    public void handleBringToTop(MPart thisPart, @UIEventTopic(UIEvents.UILifeCycle.BRINGTOTOP) Event event) {
        if (event != null && thisPart == event.getProperty(UIEvents.EventTags.ELEMENT)) {
            // code goes here
        }
    }
}

Approach 2 - Using part listeners


package com.example;

import javax.inject.Inject;

import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.osgi.service.event.Event;

public class StatusPart {

    @PostConstruct
    public StatusPart(MPart thisPart, EPartService ePartService) {
        ePartService.addPartListener(new PartListenerAdapter() {
            @Override
            public void partBroughtToTop(MPart part) {
                if (part == thisPart) {
                    // code goes here
                }
            }
        });
    }

}

Further informations