我有一个基于emf的模型。在模型中我有一个要素类和我可以添加约束的功能。例如功能A" IMPLIES"功能B.我试图使用emf命令堆栈为功能添加约束。它会为要素添加约束,但缺少属性。我的代码如下
public static Object doExecute(Feature contextFeature, FeatureModel featureModel, ComposedAdapterFactory adapterFactory) {
CreateConstraintDialog dlg = new CreateConstraintDialog(Display.getCurrent().getActiveShell(), contextFeature, featureModel, adapterFactory);
dlg.open();
// check if dialog was cancelled:
if (dlg.getReturnCode() == Window.CANCEL)
return null;
Feature selectedFeature = dlg.getSelectedFeature();
if (selectedFeature == null)
return null;
ConstraintType selectedConstraintType = dlg.getSelectedConstraintType();
Constraint constraint = FmFactory.eINSTANCE.createConstraint();
constraint.setType(selectedConstraintType);
constraint.setConstrainedFeature(selectedFeature);
constraint.setContext(contextFeature);
EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(contextFeature);
Command cmd = AddCommand.create(editingDomain, contextFeature, FmPackage.FEATURE__CONSTRAINTS, constraint);
editingDomain.getCommandStack().execute(cmd);
return null;
}
修改
当我删除constraint.setContext(contextFeature);从上面的代码中,编辑器会收到有关更改的通知(即,新的约束被添加到功能中),但由于未设置,因此缺少上下文属性。
setContext方法如下
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setContext(Feature newContext) {
if (newContext != eInternalContainer() || (eContainerFeatureID() != FmPackage.CONSTRAINT__CONTEXT && newContext != null)) {
if (EcoreUtil.isAncestor(this, newContext))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newContext != null)
msgs = ((InternalEObject)newContext).eInverseAdd(this, FmPackage.FEATURE__CONSTRAINTS, Feature.class, msgs);
msgs = basicSetContext(newContext, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FmPackage.CONSTRAINT__CONTEXT, newContext, newContext));
}
上面的代码为该功能添加了约束,但缺少上下文。任何想法
由于
答案 0 :(得分:0)
由于您刚刚创建了constraint
实例,因此无需使用命令来设置其属性,因为它尚未附加到EMF模型。你可以调用setter方法。您使用命令的地方只是将constraint
添加到现有功能。
不相关,但在执行命令之前,您还应始终在命令上调用canExecute
方法:
CompoundCommand cmd = ....;
if (cmd.canExecute()) {
editingDomain.getCommandStack().execute( cmd );
}