【问题标题】:Randomize the placement of vertices in jgraph随机化 jgraph 中顶点的位置
【发布时间】:2013-05-15 15:47:35
【问题描述】:

我在 jgraph 的帮助下创建了一个用于可视化的应用程序。我对此有几个问题。

1: 我需要根据 Vertex 对象的一个​​属性来更改 Vertices 的名称。当我使用默认设置运行应用程序时,顶点的名称打印为 Vertex@c8191c(基于顶点的更改)。我想把这个名字改成顶点的一个属性值。

2:这是最关键的一个。生成的顶点数不是静态的。数量取决于应用程序的各种其他因素,并且可以在每次应用程序运行时更改。当我使用默认设置运行此应用程序时,节点重叠,并且在第一个位置只显示一个。我需要在 jgraph 中随机分布节点。

谁能帮我解决这两个问题。如果您需要更多信息,请提及。以下是我可视化图表的代码。

public void randomizeLocations(JGraph jgraph) {
    System.out.println("Visualization 1");
    GraphLayoutCache cache = jgraph.getGraphLayoutCache();
    System.out.println("Visualization 2");
    Random r = new Random();
    for (Object item : jgraph.getRoots()) {
        System.out.println("Visualization 3");
        GraphCell cell = (GraphCell) item;
        CellView view = cache.getMapping(cell, true);
        Rectangle2D bounds = view.getBounds();
        System.out.println("next double"+r.nextDouble()*400);
        bounds.setRect(r.nextDouble() * 400, r.nextDouble() * 5,
                bounds.getWidth(), bounds.getHeight());

    }
    System.out.println("Visualization 4");
    cache.reload();
    System.out.println("Visualization 5");
    jgraph.repaint();
    System.out.println("Visualization 6");

}

提前谢谢你。

【问题讨论】:

    标签: java graph-theory jgrapht jgraph


    【解决方案1】:

    1) 覆盖 Vertices 对象的 toString 方法。

    @Override
    public String toString() {
      return "Whatever attribute you want to display here";
    }

    2) 把你的顶点放在一个 HashSet 中。这将确保仅将唯一顶点添加到您的列表中。此外,您需要覆盖 Vertices 对象的 .equals() 和 .hashCode() 方法以确保唯一性。 (见这里https://stackoverflow.com/a/27609/441692)。继续生成更多顶点,直到您的 HashSet 大小等于您想要的值。

    HashSet<Point2D.Double> unique = new HashSet<Point2D.Double>();
    Random r = new Random();
    for (Object item : jgraph.getRoots()) {
        System.out.println("Visualization 3");
        GraphCell cell = (GraphCell) item;
        CellView view = cache.getMapping(cell, true);
        Rectangle2D bounds = view.getBounds();
        int currentSize = unique.size();
        double x;
        double y;
        while (unique.size() == currentSize) {
          x = r.nextDouble() * 400;
          y = r.nextDouble() * 5;
          unique.add(new Point2D.Double(x,y));
        }
        bounds.setRect(x, y, bounds.getWidth(), bounds.getHeight());
    }
    

    【讨论】:

    • 您好,感谢您的回复。我解决了第一个问题。与第二种解决方案仍有一些混淆。我很确定应用程序会生成具有唯一属性值的不同对象。这是应用程序的一个功能。此外,它为所有顶点创建单独的节点。只是它们是重叠的。我仍然可以在 jframe 中拖动它们并将它们分开。我需要的是,我希望节点在创建时是分开的。对不起,如果我错过了什么。如果可以请进一步解释您的答案...
    • 我希望它们在 jframe 中均匀分布,尽管节点数量很多。
    • 我需要盯着你的代码,让我以编程方式移动这些节点。您可以使用相同的 HashSet 思想来确定某个节点是否已经存在于某个位置,然后以不同的方式放置它。
    • 我已经给出了下面的代码。我在不同的类中创建图表。
    • 那个代码没用。请不要把它放在答案中。只需通过编辑将其放入问题本身即可。我需要为 ListenableDirectedGraph 类生成graph 变量/代码的代码
    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多