`

连线上加文字

    博客分类:
  • GEF
阅读更多
前面写了个连线上显示文字,直接用的label,那样确实简单,但有的时候还是需要独立出来,这个时候就要有单独的控制器,原理很简单:即文字是连线的子节点,然后将文字添加到连线上面,就OK了;实现父子关系很简单:在连线控制器中添加getChildren方法就OK了,然后将文字绑定到连线上面就是刷新的时候确定连线的上的坐标然后绑定Label就可以了,直接上代码:
protected void refreshVisuals() {
		// String text = getLabelWrapper().getText();
		Label label = (Label) getFigure();
		String text = label.getText();
		if (text == null || text.equals("")) {
			text = ((LabelModel) getModel()).getText();
		}
		//
		Polyline polyline = (Polyline) ((CustomAbstractConnectionEditPart) getParent()).getConnectionFigure();
		Point location = ((LabelModel) getModel()).getLocation();
		if (location == null) {
			location = calculateInitialLocation(polyline, text);
			((LabelModel) getModel()).setLocation(location);
		}
		label.setText(text);
		LabelConstraint constraint = new LabelConstraint(text, location, polyline);
		((GraphicalEditPart) getParent()).setLayoutConstraint(this, getFigure(), constraint);
	}
	private Point calculateInitialLocation(Polyline polyline, String text) {
		Dimension textDimension = FigureUtilities.getTextExtents(text, figure.getFont());
		return new Point(-(textDimension.width + 5), -(textDimension.height + 5));
	}private class LabelConstraint implements Locator {
		String text;
		Point relativeLocation;
		Polyline polyline;

		public LabelConstraint(String text, Point location, Polyline polyline) {
			this.text = text;
			this.relativeLocation = location;
			this.polyline = polyline;
		}
		public void relocate(IFigure figure) {
			Dimension minimum = FigureUtilities.getTextExtents(text, figure.getFont());
			figure.setSize(minimum);
			Point midPoint = polyline.getPoints().getMidpoint();
			Point newLocation = relativeLocation.getCopy();
			newLocation.translate(midPoint);
			figure.setLocation(newLocation);
		}
	}
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics