3

I have a single vertex (vertex A)being connected to two different vertices(B & C) . But it gets duplicated and shows the same vertex (A)being connected to the two different vertices(B & C). How can I make a single vertex (A) with 2 edges coming out and being connected to B & C.

    for (int i = 0; i < cardList.getSize(); i++) {
        try {

            Object v1 = graph.insertVertex(graph.getDefaultParent(), null, Card, x, y, cardWidth, cardHeight);
            Object v2 = graph.insertVertex(graph.getDefaultParent(), null, card.getConnectedCard(i), x + cardWidth + 50, y, cardWidth, cardPanelHeight);
            Object e1 = graph.insertEdge(graph.getDefaultParent(), null, "", v1, v2);

        } finally {
            graph.getModel().endUpdate();
        }
    }
Frodo Baggins
  • 8,290
  • 6
  • 45
  • 55
span
  • 75
  • 6

1 Answers1

1

The problem is that you are calling insertVertex multiple times. Each time, a new vertex will be created. Although I'm not really familiar with JGraphX, and the code provided so far was far from being compilable, the problem can likely be solved by inserting the vertices and the edges separately:

// First, insert all vertices into the graph, and store
// the mapping between "Card" objects and the corresponding
// vertices
Map<Card, Object> cardToVertex = new LinkedHashMap<Card, Vertex>();
for (int i = 0; i < cardList.getSize(); i++) 
{
    Card card = cardList.get(i);
    Object vertex = graph.insertVertex(
        graph.getDefaultParent(), null, card, x, y, cardWidth, cardHeight);
    cardToVertex.put(card, vertex);
}        

// Now, for each pair of connected cards, obtain the corresponding
// vertices from the map, and create an edge for these vertices
for (int i = 0; i < cardList.getSize(); i++) 
{
    Card card0 = cardList.get(i);
    Card card1 = card0.getConnectedCard(i);

    Object vertex0 = cardToVertex.get(card0);
    Object vertex1 = cardToVertex.get(card1);
    Object e1 = graph.insertEdge(
        graph.getDefaultParent(), null, "", vertex0, vertex1);
}        
Marco13
  • 53,703
  • 9
  • 80
  • 159