GEF常见问题3:自身连接

在类图里能看到一些对象具有对自己的引用,通常这些引用用于表达树状结构,即父子节点都是同一类对象。用GEF绘制这样的连接线一般是通过转折点(Bendpoint)实现的,如果你的GEF应用程序里还不能使用Bendpoint,请按照上一篇介绍的步骤添加对Bendpoint的支持。

原先我们的GefPractice应用程序是不允许一条连接线的起点和终点都是同一个图形的,因为这样会导致连接线缩成一个点隐藏在图形下方,用户并不知道它的存在。当时我们在CreateConnectionCommand类的canExecute()方法里进行了如下判断:

public boolean canExecute() {
    
if (source.equals(target))
        
return false;
    
}

因此现在首先要把这两句删除。然后在execute()方法里对自身连接的这种情况稍做处理,处理的方法是给这条连接线在适当位置增加三个Bendpoint,你也可以根据想要的连接线形状修改Bendpoint的数目和位置。

public void execute() {
    connection 
= new Connection(source, target);
    
if (source == target) {
        
//The start and end points of our connection are both at the center of the rectangle,
        
//so the two relative dimensions are equal.
        ConnectionBendpoint cbp = new ConnectionBendpoint();
        cbp.setRelativeDimensions(
new Dimension(0-60), new Dimension(0-60));
        connection.addBendpoint(
0, cbp);
        ConnectionBendpoint cbp2 
= new ConnectionBendpoint();
        cbp2.setRelativeDimensions(
new Dimension(100-60), new Dimension(100-60));
        connection.addBendpoint(
1, cbp2);
        ConnectionBendpoint cbp3 
= new ConnectionBendpoint();
        cbp3.setRelativeDimensions(
new Dimension(1000), new Dimension(1000));
        connection.addBendpoint(
2, cbp3);
    }
}

现在用户只要选择连接工具,然后在一个节点上连续点两下就可以创建自身连接了,如下图所示。


自身连接

点此下载工程,此工程修改自GEF常见问题2中的GefPractice-bp,目标文件扩展名为.gefpracticesc。

posted @ 2006-06-22 11:05  八进制  阅读(5972)  评论(16编辑  收藏  举报

博客已搬家:bjzhanghao.com