Question

I'm trying to create a graph which is GRID layout by using JUNG. and i couldn't find how, Is there anyway to create a graph by using JUNG

Thanks in advance

Was it helpful?

Solution

I am not sure whether JUNG directly supports a GridLayout using any of its layout managers. However it is possible to create a grid based layout by adding vertices to a StaticLayout and then changing the position of each vertex according to its coordinates in the grid.

import edu.uci.ics.jung.algorithms.layout.*;
import edu.uci.ics.jung.graph.*;
import edu.uci.ics.jung.visualization.*;
import edu.uci.ics.jung.visualization.control.*;
import java.awt.*;
import javax.swing.*;

public class JungGridLayout extends JFrame {

Graph graph;
StaticLayout layout;
VisualizationViewer vv;

public static void main(String[] args) {
    JungGridLayout g = new JungGridLayout(25,5,5);
}

public JungGridLayout(int numNodes, int numRows, int numColumns) {
    graph = new SparseMultigraph();
    layout = new StaticLayout(graph);

    //distance between the nodes
    int distX=100;
    int distY=100;

    //idea is to add the vertices and change and the position of each vertex to a coordinate in a grid
    for (int n=0;n<numNodes;n++) {
        graph.addVertex(String.valueOf(n));
    }

    int operatingNode = 0;

    for (int i=0;i<numRows;i++) {
        for (int j=0;j<numColumns;j++) {
            layout.setLocation(String.valueOf(operatingNode++), i*distX, j*distY);
        }
    }        

    createVisualization();
    createFrame();
}

public void createFrame() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
}

public void createVisualization() {
    vv = new VisualizationViewer(layout, new Dimension(800, 600));

    //zooming and transforming
    GraphZoomScrollPane zoomPane = new GraphZoomScrollPane(vv);
    DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);

    this.getContentPane().add(zoomPane);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top