When using the Eclipse Rich Client Platoform (E4 specifically), there exist various ways on how to get notified when a part is made visible to the user.

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

A note about Netcup (advertisement)

Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).