In last blog post I talked about the problem that people (including me!) often forget to set the contributorURI
of the MApplicationElement
instance which could lead to problems.
So with the next release of e(fx)clipse there’s a new service called ModelElementFactory
who does the initialization for you and has some other nice features.
Let’s see how we can create model instances:
import org.eclipse.fx.ui.workbench.services.ModelService; import org.eclipse.fx.ui.workbench.services.ModelService.ModelElementFactory; import org.eclipse.e4.ui.workbench.modeling.EModelService; class Handler { @Execute public void createPart(EModelService eModelService, ModelService modelService) { ModelElementFactory factory = modelService.createModelElementFactory(getClass(),eModelService); MPart part = factory.createModelElement(MPart.class); // Creates the instance and sets the contributorURI // ... } }
You might ask why does one have to create the service instance through the ModelService as the factory and the problem is that:
- we need the EModelService-Instance
- we need access to the owner of the final element which we can only extract from the caller-class
While 1. can be worked around with the an IContextFunction
the 2nd problem is not easy to solve (although it can be solved and I’ll introduce the solution in an upcoming blog post)
So the first API provided solves our basic usecase of creating application model elements but there’s more
- Post processing of created instances
MPart part = factory.createModelElement(MPart.class, this::fillPart); private MPart fillPart(MPart part) { // initialize the part }
- Creation of Supplier instances you can pass around
class Handler { @Execute public void createPart(EModelService eModelService, ModelService modelService) { ModelElementFactory factory = modelService.createModelElementFactory(getClass(),eModelService); Supplier<MPart> part = factory.createModelElementCreator(MPart.class, this::fillPart) // ... } } public class EditorOpener { public void createOrSelectPart(MPartStack stack, String elementId, Supplier<MPart> partCreator) { // do some logic eg detecting of the elementId already exists MPart part = partCreator.get(); partStack.getChildren().add(part); return part; } }
Pingback: When an IContextFunction does not solve your problem – and the solution with e(fx)clipse 2.2.0 | Tomsondev Blog