GMF中,删除节点和连线的另一种实现

问题

在GMF中,如果需要programmatically删除节点或连线,在google中我们很容易搜索到《GMF中,删除节点和连线的实现》一文(我并不确定这是原创作者的原始链接),很多人可能都使用这种实现。这是一种很好的实现,但有时候也有其缺点--除了需要删除View和Edge外,还需要删除model,在element对应于各种不同的model时,显然需要写大量if else来处理不同的model。

实现

我们可以有另一种实现,通过request和command来实现,以下代码删除某个节点上所有的连线

	public void deleteConnections(ShapeNodeEditPart editpart)
	{
		CompoundCommand compoundCommand =new CompoundCommand("delete all connections");
		List connections = editpart.getTargetConnections();
		connections.addAll(editpart.getSourceConnections());
		GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
		deleteReq.setEditParts(connections);
		for (int i = 0; i < connections.size(); i++) {
			EditPart object = (EditPart) connections.get(i);
			Command deleteCmd = object.getCommand(deleteReq);
			if (deleteCmd != null)
				compoundCommand.add(deleteCmd);
		}
		
		editpart.getDiagramEditDomain().getDiagramCommandStack().execute(compoundCommand);
	}

删除多个节点

public void deleteNodes(List editparts)
	{
		CompoundCommand compoundCommand =new CompoundCommand("delete nodes");
		GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE);
		
		deleteReq.setEditParts(editparts);
		for (int i = 0; i < editparts.size(); i++) {
			EditPart object = (EditPart) editparts.get(i);
			Command deleteCmd = object.getCommand(deleteReq);
			if (deleteCmd != null)
				compoundCommand.add(deleteCmd);
		}
		
		((ShapeNodeEditPart)editparts.get(0)).getDiagramEditDomain().getDiagramCommandStack().execute(compoundCommand);
	}

这种方式的好处是,不必关心底层model的删除,因为每个element对应的command中,GMF已经帮我们实现了,更加简单,且符合开放-闭合原则。并且,undo和redo也已经实现。

 

参考

org.eclipse.gef.ui.actions.DeleteAction

 

Binhua Liu原创,写于2013/8/25。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值