Skip to content

Month: February 2011

Learning JUNG – Java Universal Network/Graph Framework

I’m searching for “user-friendly” java graph frameworks for an application that I’m developing for my studies. I stumbled upon JUNG. After 15 minutes searching and reading, I managed to create a directed graph and show it on screen.

package com.vainolo;

import java.awt.Dimension;
import javax.swing.JFrame;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.visualization.VisualizationImageServer;

public class JungLearning {
  public static void main(String[] args) {
    DirectedSparseGraph g = new DirectedSparseGraph();
    g.addVertex("Vertex1");
    g.addVertex("Vertex2");
    g.addVertex("Vertex3");
    g.addEdge("Edge1", "Vertex1", "Vertex2");
    g.addEdge("Edge2", "Vertex1", "Vertex3");
    g.addEdge("Edge3", "Vertex3", "Vertex1");
    VisualizationImageServer vs =
      new VisualizationImageServer(
        new CircleLayout(g), new Dimension(200, 200));

    JFrame frame = new JFrame();
    frame.getContentPane().add(vs);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

And this is the output graph:

You can fetch this example’s code here

Next step: Try to show labels and try to change the vertex shapes.