一、新建模型结点
installEditPolicy(EditPolicy.CONTAINER_ROLE, new DiagramContainerEditPolicy());
public class DiagramContainerEditPolicy extends ContainerEditPolicy {
@Override
protected Command getCreateCommand(CreateRequest request) {
AddHelloWorldCommand command = new AddHelloWorldCommand(
(DiagramRootContent) getHost().getModel(),
(HelloWorldModel) request.getNewObject());
return command;
}
}
public static final String P_CHILDREN = "p_children";
public void addChild(HelloWorldModel child) {
if (!children.contains(child)) {
children.add(child);
firePropertyChange(P_CHILDREN, null, child);
}
}
public void removeChild(HelloWorldModel child) {
if (children.contains(child)) {
children.remove(child);
firePropertyChange(P_CHILDREN, child, null);
}
}
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals(DiagramRootContent.P_CHILDREN)){
refreshChildren();
}
}
@Override
public void activate() {
super.activate();
((DiagramRootContent)getModel()).addPropertyChangeListener(this);
}
@Override
public void deactivate() {
((DiagramRootContent)getModel()).removePropertyChangeListener(this);
super.deactivate();
}
图一
呵呵,图已经被成功加上。只是有一点:每次都加在重一位置。回想一下:我们在建一个新的模型时,没有给他设置一个位置,因此用的都是我们缺省定义的位置,所以每次都被加到同一位置上去了。
这个修改很容易,就是修改DiagramContainerEditPolicy的getCreateCommand()方法,让它再传一个位置参数给AddHelloWorldCommand,修改后最终的代码如下:
public class DiagramContainerEditPolicy extends ContainerEditPolicy {
@Override
protected Command getCreateCommand(CreateRequest request) {
AddHelloWorldCommand command = new AddHelloWorldCommand(
(DiagramRootContent) getHost().getModel(),
(HelloWorldModel) request.getNewObject());
command.setLocation(request.getLocation());
return command;
}
}
和:
public class AddHelloWorldCommand extends Command {
private DiagramRootContent content;
private HelloWorldModel model;
public AddHelloWorldCommand(DiagramRootContent content,
HelloWorldModel model) {
super();
this.content = content;
this.model = model;
}
@Override
public void execute() {
content.addChild(model);
}
@Override
public void undo() {
content.removeChild(model);
}
public void setLocation(Point location) {
Rectangle constraints = model.getConstraints();
constraints.setLocation(location);
}
}
OK,现在再试一下:
图二
现在图形被加到了正确的位置上了。