关键字:Draw2d、锚点、TriangleAnchor
连线的时候能不能连接到画的图中去,在连线二中已经提到了,简单的跟图形连在一起,但是对于特殊的图是有不同的需求的。
如三角形,怎样连接端点。
public class TriangleAnchor extends ChopboxAnchor {
public TriangleAnchor(Triangle triangle) {
super(triangle);
}
public Point getLocation(Point reference) {
Rectangle r = Rectangle.SINGLETON;
r.setBounds(getBox());
r.resize(-1, -1);
int size;
size = Math.min(r.height, r.width / 2);
r.y += (r.height - size) / 2;
size = Math.max(size, 1); //Size cannot be negative
Point head, p2, p3;
int d1,d2,d3;
head = new Point(r.x + r.width / 2, r.y);
p2 = new Point (head.x - size, head.y + size);
p3 = new Point (head.x + size, head.y + size);
Point p;
if(Math.abs(reference.x-p2.x)+Math.abs(reference.y-p2.y) >
Math.abs(reference.x-p3.x)+Math.abs(reference.y-p3.y)) {
p = p3;
} else {
p = p2;
}
d1 = distance(reference,head);
d2 = distance(reference,p2);
d3 = distance(reference,p3);
p = head;
if(d1<d2 && d1<d3) {
p = head;
}
if(d2<d1 && d2<d3) {
p = p2;
}
if(d3<d1 && d3<d2) {
p = p3;
}
return p;
}
private int distance(Point p1, Point p2) {
return Math.abs(p1.x-p2.x)+Math.abs(p1.y-p2.y);
}
}
public class HelloWorld2 {
public static void main(String args[]) {
Shell shell = new Shell();
shell.setText("Draw2d Hello World");
shell.setSize(400, 400);
shell.open();
// create content 4 shell.
createContent4Shell(shell);
while (!shell.isDisposed ()) {
if (!Display.getDefault().readAndDispatch ())
Display.getDefault().sleep ();
}
}
private static void createContent4Shell(Shell shell) {
Panel rootFigure = new Panel();
rootFigure.setLayoutManager(new XYLayout());
IFigure figure1 = new Ellipse();
// Label figure2 = new Label("ddddddddddddddddd");
Triangle figure2 = new Triangle();
// --------------------------------------------------------
// add connection
PolylineConnection connection = new PolylineConnection();
connection.setSourceAnchor(new ChopboxAnchor(figure1));
connection.setTargetAnchor(new TriangleAnchor(figure2));
// add connection
// --------------------------------------------------------
rootFigure.add(figure1,new Rectangle(10,10,60,30));
rootFigure.add(figure2,new Rectangle(80,90,90,190));
rootFigure.add(connection);
LightweightSystem lws = new LightweightSystem(shell);
lws.setContents(rootFigure);
}
}
这个端点的求法,没有考虑三角形的方向,计算方法参考:
package org.eclipse.draw2d;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PointList;
import org.eclipse.draw2d.geometry.Rectangle;
/**
* A triangular graphical figure.
*/
public final class Triangle
extends Shape
implements Orientable