Draw2d入门系列(三、实现Connection)
利用Draw2d中的Router、Anchor和Locator,可以实现多种连接样式。其中Router负责连接线的外观和操作方式,最简单的是设置Router为NULL(无 Router),这样会使用直线连接,其他连接方式包括折线、具有控制点的折线等,若想控制连接不互相交叉也需要在Router中做文章。
Anchor控制连线端点在图形上的位置,即“锚点”的位置,最易于使用的是ChopBoxAnchor,它先假设图形中心为连接点,然后计算这条假想连线与图形边缘的交汇点座位实际的锚点,其他Anchor,还有EllipseEAnchor、LabelAnchor和XYAnchor等。
Locator的作用是定位图形,例如希望在连接中点处以一个标签显示此链接的名称,就可以使用MidpointLocator来帮助定位这个标签,其他Locator还有ArrowLocator用于定位可旋转的修饰(Decoration,例如PolygonDecoration)、BendpointerLocator用于定位链接控制点、ConnectionEndpointLocator用于定位连接端点(通过制定uDistance和vDistance属性的值可以设置以端点为原点的坐标
实现简单图形的连接只要设置好连线的对应的锚点即可,下面是我给出的例子,通过PolylineConnection建立了node1和node2的连线,并且设置了node1和node2拖动的监听器,用户可以拖动图形到窗口的任意位置
package com.heming.draw2d.demo;import org.eclipse.swt.widgets.Shell;import org.eclipse.swt.widgets.Display;import org.eclipse.draw2d.*;import org.eclipse.draw2d.geometry.*;/** * 连线的实现 * * @author 何明 * */public class Connection {public static void main(String args[]) {Shell shell = new Shell();shell.setSize(350, 350);shell.open();shell.setText("Connection Demo");LightweightSystem lws = new LightweightSystem(shell);IFigure panel = new Figure();lws.setContents(panel);// 创建两个四边形的图形实例RectangleFigure node1 = new RectangleFigure(), node2 = new RectangleFigure();// 设置node1的背景色node1.setBackgroundColor(ColorConstants.red);// 设置node1的大小和位置node1.setBounds(new Rectangle(30, 30, 64, 36));// 设置node2的背景色node2.setBackgroundColor(ColorConstants.blue);// 设置node2的大小和位置node2.setBounds(new Rectangle(100, 100, 64, 36));// 创建一个连线的实例PolylineConnection conn = new PolylineConnection();// 设置连线起点的锚点conn.setSourceAnchor(new ChopboxAnchor(node1));// 设置连线目标的锚点conn.setTargetAnchor(new ChopboxAnchor(node2));// 设置连线目标的装饰器conn.setTargetDecoration(new PolygonDecoration());Label label = new Label("Midpoint");label.setOpaque(true);label.setBackgroundColor(ColorConstants.buttonLightest);label.setBorder(new LineBorder());// 添加连线的Locatorconn.add(label, new MidpointLocator(conn, 0));// 在底层Figure中添加子Figurepanel.add(node1);panel.add(node2);panel.add(conn);// 添加node1拖动的监听器new Dragger(node1);// 添加node2拖动的监听器new Dragger(node2);Display display = Display.getDefault();while (!shell.isDisposed()) {if (!display.readAndDispatch())display.sleep();}}/** * 实现对图形的移动进行监听 * @author 何明 * */static class Dragger extends MouseMotionListener.Stub implements MouseListener{public Dragger(IFigure figure){figure.addMouseMotionListener(this);figure.addMouseListener(this);}Point last;@Overridepublic void mouseDoubleClicked(MouseEvent e) {}@Overridepublic void mousePressed(MouseEvent e) {last = e.getLocation();}@Overridepublic void mouseReleased(MouseEvent e) {}@Overridepublic void mouseDragged(MouseEvent e) {Point p = e.getLocation();Dimension delta = p.getDifference(last);last = p; Figure f = (Figure) e.getSource();//设置拖动的Figure的位置f.setBounds(f.getBounds().getTranslated(delta.width,delta.height));}}