XYLayout: 子图形可以在上面随意改变大小和位置
1: 父EditPart中添加布局管理器
public class ContentsEditPart extends AbstractGraphicalEditPart {
protected IFigure createFigure() {
Layer figure = new Layer(); //图层
figure.setLayoutManager(new XYLayout());
return figure;
}
......
}
2: 为子模型添加约束Constraint
为了使用XYLayout,需要设置被该布局管理器管理的图形对象的尺寸和位置(约束Constraint), 对图形集ContentsModel 中的每个图形都要添加约束,约束被添加到他们的模型类中.
public class HelloModel {
private String text = "Hello world";
private Rectangle constraint;
...
public Rectangle getConstraint() {
return constraint;
}
public void setConstraint(Rectangle constraint) {
this.constraint = constraint;
}
}
3: 在子EditPart中把约束施加给图形.
public class HelloEditorPart extends AbstractGraphicalEditPart {
...
protected void refreshVisuals() {
Rectangle constraint = ((HelloModel)getModel()).getConstraint();
((GraphicalEditPart)getParent()).setLayoutConstraint(this,getFigure(),constraint);
}
...
}
4: 绘制带约束的图形
public class DiagramEditor extends GraphicalEditor {
...
protected void initializeGraphicalViewer() {
viewer = getGraphicalViewer();
ContentsModel parent = new ContentsModel(); //父模型
HelloModel child1=new HelloModel(); //子模型
child1.setConstraint(new Rectangle(0,0,-1,-1)); //添加约束
parent.addChildren(child1);
HelloModel child2=new HelloModel();
child2.setConstraint(new Rectangle(30,30,-1,-1));
parent.addChildren(child2);
HelloModel child3=new HelloModel();
child3.setConstraint(new Rectangle(10,80,80,50));
parent.addChildren(child3);
viewer.setContents(parent);
}
...
}
代码: 下载