Home > Articles > Programming > Java

📄 Contents

  1. JGraph Intro
  2. Component Architecture
  3. Conclusion
  • Print
  • + Share This
Like this article? We recommend

Component Architecture

Figure 1’s sample graph presents a high-level overview of JGraph’s architecture, in terms of various important classes and interfaces. One of the classes revealed in that figure is JGraph. Because that class serves as the entry point to the JGraph component, it makes sense to begin exploring some key areas of JGraph’s architecture by focusing on JGraph.

JGraph Class

Like the entry-point classes to Swing’s components, such as javax.swing.JTree, JGraph is organized around the model-delegate architecture. JGraph maintains references to the component’s graph model and selection model. JGraph also maintains a reference to its UI delegate, which displays the graph, in terms of its views, and handles events.

JGraph provides several constructors, such as the no-argument constructor seen in Listing 1, for creating JGraph components. JGraph also provides many methods for configuring this component. Four of those methods appear below:

  • public void setCloneable(boolean flag) clones vertices and edges during a Ctrl-drag operation when flag is true.
  • public void setGridVisible(boolean flag) displays a grid when flag is true. This grid makes it possible to more accurately position vertices and edges.
  • public void setHandleSize(int size) sets the size of the selected vertex’s/edge’s handles to size.
  • public void setScale(double newValue) sets the current scale of the graph based on the value passed in newValue. For example, a value of 2.0 would scale the graph to twice its default size.

The setCloneable() method has already been demonstrated. For a demonstration of the remaining three methods, make the following change to Listing 1’s SampleGraph.java source code: Replace this line of code:

getContentPane ().add (new JScrollPane (new JGraph ()));

with the following code fragment:

graph = new JGraph ();
graph.setGridVisible (true);
graph.setHandleSize (5);
graph.setScale (1.5);
getContentPane ().add (new JScrollPane (graph));

After compiling the changed SampleGraph.java source file and running the application, you should observe output similar to Figure 8.

Figure 8

Figure 8 JGraph methods let you display a grid, set the size of handles, scale a graph, and more.

Graph Model

The graph model maintains a graph’s data and is an instance of a class that implements the org.jgraph.graph.GraphModel interface, such as org.jgraph.graph.DefaultGraphModel. Various JGraph constructors take a GraphModel argument that specifies the graph model when the component is created. If you invoke a JGraph constructor that does not take a GraphModel argument (such as the no-argument constructor), the graph model is created behind the scenes as an instance of DefaultGraphModel. You can override the current graph model by invoking JGraph’s public void setModel(GraphModel newModel) method. To obtain the graph model currently being used, invoke JGraph’s public GraphModel getModel() method.

The code fragment below, which I excerpted from c:\jgraph\examples\org\jgraph\example\HelloWorld.java, creates a graph model based on an instance of the DefaultGraphModel class and then passes that object to JGraph’s public JGraph(GraphModel model) constructor to establish the object as the new JGraph component’s graph model:

GraphModel model = new DefaultGraphModel ();
JGraph graph = new JGraph (model);

Graph data consists of cells, the graph structure, and the group structure.

A cell represents a vertex, an edge, or a port—a connection point for a vertex (the port belongs to the vertex). Vertices are instances of classes that implement the org.jgraph.graph.GraphCell interface, such as org.jgraph.graph.DefaultGraphCell. Similarly, edges (which connect vertices to each other by plugging into their ports) are instances of classes that implement the org.jgraph.graph.Edge interface, such as org.jgraph.graph.DefaultEdge, and ports are instances of classes that implement the org.jgraph.graph.Port interface, such as org.jgraph.graph.DefaultPort.

Cells can have attributes such as background and foreground colors, and whether or not they are editable (the cell’s content can be modified). These attributes are stored in attribute maps as key-value pairs. When you create a cell, you can pass an org.jgraph.graph.AttributeMap object to an appropriate constructor for holding the cell’s attributes. If you invoke a constructor that does not take an AttributeMap argument, an AttributeMap is created behind the scenes.

AttributeMap provides a public AttributeMap getAttributes() method for retrieving a cell’s attribute map. You will typically call that method along with various methods in the org.jgraph.graph.GraphConstants class to establish a cell’s attributes. The code fragment below, which I excerpted from HelloWorld.java, creates a vertex with an attached port. It then calls various GraphConstants methods to set the cell’s boundaries, gradient color, opaqueness, and border (or border color) attributes. The first argument passed to those methods is the cell’s attribute map, which is returned via a call to the cell’s getAttributes() method:

public static DefaultGraphCell createVertex (String name, double x, double y, double w, double h, 
                       Color bg, boolean raised) 
  DefaultGraphCell cell = new DefaultGraphCell (name);

  GraphConstants.setBounds (cell.getAttributes (), new Rectangle2D.Double (x, y, w, h));

  if (bg != null) 
    GraphConstants.setGradientColor (cell.getAttributes (), Color.orange);
    GraphConstants.setOpaque (cell.getAttributes (), true);

  if (raised)
    GraphConstants.setBorder (cell.getAttributes (), BorderFactory.createRaisedBevelBorder ());
    GraphConstants.setBorderColor (cell.getAttributes (), Color.black);

  DefaultPort port = new DefaultPort ();
  cell.add (port);

  return cell;

The graph structure provides a graph’s connectivity information, which is defined using ports that serve as each edge’s source and target. The overall geometric pattern that describes a graph (its layout) is not part of the graph structure.

GraphModel provides several methods for accessing the graph structure. These methods include public Iterator edges(Object port) for iterating over a port’s edges, public Object getSource(Object edge) for returning edge’s source port, and public Object getTarget(Object edge) for returning edge’s target port.

In addition to accessing the graph structure, we can establish that structure by invoking Edge’s public void setSource(Object port) and public void setTarget(Object port) methods. Those methods establish the source and target ports to which an edge connects. The following code fragment (once again excerpted from HelloWorld.java) demonstrates these methods. After creating a pair of vertices, an edge is created and attached to each vertex’s port:

DefaultGraphCell [] cells = new DefaultGraphCell [3];

cells [0] = createVertex ("Hello", 20, 20, 40, 20, null, false);
cells [1] = createVertex ("World", 140, 140, 40, 20, Color.ORANGE, true);

DefaultEdge edge = new DefaultEdge ();

edge.setSource (cells [0].getChildAt (0));
edge.setTarget (cells [1].getChildAt (0));
cells [2] = edge;

The group structure provides a means to nest a graph’s cells into part-whole hierarchies. This structure is analogous to the Abstract Windowing Toolkit’s relationship between components and containers, where a container is considered to be a component with a containment capability. Just as a container’s components can be manipulated as if they were one component, the group structure makes it possible to manipulate a group of cells as if they were one cell.

Internally, the group structure is organized as a sequence of trees. Each tree’s root can describe a vertex or an edge, or can serve as a placeholder for a group. GraphModel’s public int getRootCount() method returns the number of roots and its public Object getRootAt(int index) method returns the root located at index. After you have the roots, you can begin traversing each tree to obtain the entire group structure by invoking other GraphModel methods such as public int getChildCount(Object parent)—to obtain the number of child cells for a given parent (a port is always a child of a vertex, for example)—and public Object getChild(Object parent, int index)—to return parent’s child located at index.

The concept of group structure may seem somewhat confusing. To overcome that confusion, I have created a Java application that dumps out the group structure (and provides some graph structure information) for the sample graph that appears in Figure 1. Listing 2 presents this application’s source code.

Listing 2 SampleGraph2.java

// SampleGraph2.java

import org.jgraph.JGraph;
import org.jgraph.graph.*;

import java.util.*;
import javax.swing.*;

public class SampleGraph2 extends JFrame
  JGraph graph;

  public SampleGraph2 (String title)
   super (title);

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   graph = new JGraph ();
   getContentPane ().add (new JScrollPane (graph));

   pack ();

   setVisible (true);

  public static void main (String [] args)
   SampleGraph2 sg = new SampleGraph2 ("Sample Graph 2");

   GraphModel gm = sg.graph.getModel ();

   dumpGroupStructure (gm);

  public static void dumpGroupStructure (GraphModel gm)
   for (int i = 0; i < gm.getRootCount (); i++)
      Object o = gm.getRootAt (i);
      System.out.println ("\n" + o + ": " + classify (gm, o));
      dumpGroup (gm, o, 1);

  public static void dumpGroup (GraphModel gm, Object o, int level)
   for (int i = 0; i < gm.getChildCount (o); i++)
      for (int j = 0; j < 3 * level; j++)
        System.out.print (" ");

      Object c = gm.getChild (o, i);
      System.out.println (c + ": " + classify (gm, c));
      if (c != null)
        dumpGroup (gm, c, level+1);

  public static String classify (GraphModel gm, Object o)
   if (gm.isEdge (o))
     return "Edge [Source = " + gm.getSource (o) +
         ", Target = " + gm.getTarget (o) + "]";
   if (gm.isPort (o))
     return "Port";
     return "Vertex or Group";

Listing 2 demonstrates various GraphModel methods. Along with previously described methods, you discover public boolean isEdge(Object edge) for determining if the cell that edge identifies is an edge (true) or not (false), and public boolean isPort(Object port) for finding out whether the cell that port identifies is a port (true) or not (false).

When you run SampleGraph2, you discover the following output. Compare this output to the graph you see in Figure 1:

model: Edge [Source = JGraph/Center, Target = GraphModel/Center]

ui: Edge [Source = JComponent/Center, Target = ComponentUI/Center]

ModelGroup: Vertex or Group
  GraphModel: Vertex or Group
   GraphModel/Center: Port
  DefaultGraphModel: Vertex or Group
   DefaultGraphModel/Center: Port
  implements: Edge [Source = GraphModel/Center, Target = DefaultGraphModel/Center]

JComponent: Vertex or Group
  JComponent/Center: Port

JGraph: Vertex or Group
  JGraph/Center: Port

extends: Edge [Source = JComponent/Center, Target = JGraph/Center]

UIGroup: Vertex or Group
  ComponentUI: Vertex or Group
   ComponentUI/Center: Port
  GraphUI: Vertex or Group
   GraphUI/Center: Port
  BasicGraphUI: Vertex or Group
   BasicGraphUI/Center: Port
  implements: Edge [Source = GraphUI/Center, Target = BasicGraphUI/Center]
  extends: Edge [Source = ComponentUI/Center, Target = GraphUI/Center]

The presence of Vertex or Group in the output indicates that we are dealing with either a vertex (as in JGraph: Vertex or Group) or a group (such as UIGroup: Vertex or Group).

Now that you have a basic understanding of cells, graph structure, and group structure, you might be wondering how to add cells to a graph model. GraphModel comes to the rescue by providing a public void insert(Object [] roots, Map attributes, ConnectionSet cs, ParentMap pm, UndoableEdit [] e) method:

  • roots describes the graph’s roots. Consult the earlier discussion of group structure for more information on roots.
  • attributes describes a map of cell-attribute map pairs. This map can be used to conveniently apply common attributes to multiple cells.
  • cs describes a set of connections between vertices and edges. This set is created from the org.jgraph.graph.ConnectionSet class.
  • pm describes a map of relationships between child cells and parent cells. This map is created from the org.jgraph.graph.ParentMap class.
  • e describes an array of undoable edits. This array is created from the javax.swing.undo.UndoableEdit class.

The insert() method looks complicated, but is not that hard to use. To prove that to you, I have prepared an alternative code fragment to HelloWorld.java’s graph.getGraphLayoutCache ().insert (cells); code fragment—for inserting cells into the graph model.

After creating two attribute maps, where the first attribute map associates cells with their own attribute maps and the second attribute map associates the sizeable attribute—do not resize—with each cell, the code fragment creates a connection set that registers a single connection between the edge and each vertex’s port. It then inserts the graph’s three roots (both vertices and the edge), the first attribute map, and the connection set into the graph model:

Map<DefaultGraphCell,Map> graphAttr = new Hashtable ();

Map cellAttr = new Hashtable ();

GraphConstants.setSizeable (cellAttr, false);

graphAttr.put (cells [0], cellAttr);
graphAttr.put (cells [1], cellAttr);

ConnectionSet cs = new ConnectionSet (edge, cells [0], cells [1]);
model.insert (new Object [] { edge, cells [0], cells [1] },
       graphAttr, cs, null, null);

I pass null for both the parent map and undoable edit array because they are not required. (I have nothing further to say about them in this introductory article.)

You are probably wondering what happens when cellAttr contains an entry with the same attribute name as found in a cell’s own attribute map (cells [0].getAttributes (), for example), but having a different value. Which value takes precedence? Experiments reveal that precedence is given to the value in cellAttr’s entry.

Selection Model

The selection model maintains a graph’s selection data and is an instance of a class that implements the org.jgraph.graph.GraphSelectionModel interface, such as org.jgraph.graph.DefaultGraphSelectionModel. You can override the current selection model by invoking JGraph’s public void setSelectionModel(GraphSelectionModel selectionModel) method. To obtain the selection model currently being used, invoke JGraph’s public GraphSelectionModel getSelectionModel() method. The code fragment below creates a JGraph object and then calls getSelectionModel()to retrieve the JGraph object’s selection model:

JGraph graph = new JGraph ();
GraphSelectionModel gsm = graph.getSelectionModel ();

Graph selection data consists of the selection mode and those cells that have been selected.

The selection mode determines whether single cells or multiple cells can be selected, and is described by two GraphSelectionModel constants: SINGLE_GRAPH_SELECTION and MULTIPLE_GRAPH_SELECTION. These constants are passed to GraphSelectionModel’s public void setSelectionMode(int mode) method to change the selection mode according to the constant specified by mode. The current selection mode can be obtained by invoking the counterpart public int getSelectionMode() method. The code fragment below builds onto the earlier code fragment by invoking setSelectionMode() to change from the default multiple graph selection mode to single graph selection mode:

gsm.setSelectionMode (GraphSelectionModel.SINGLE_GRAPH_SELECTION);

Various GraphSelectionModel methods can be called to obtain information about the current selection. For example, public int getSelectionCount() returns the number of cells in the selection, and the public Object [] getSelectionCells() method returns an array of all selected cells.

You can receive notification when the selection changes. Accomplish this task by adding a graph selection listener to your JGraph object via the public void addGraphSelectionListener(GraphSelectionListener gsl) method. The org.jgraph.event.GraphSelectionListener interface provides a public void valueChanged(GraphSelectionEvent e) method that gets called whenever the selection changes. The org.jgraph.event.GraphSelectionEvent object that is passed to this method provides a public Object [] getCells() method for returning an array of those cells that have been added to or removed from the selection, and a public boolean isAddedCell(Object cell) method that returns true if cell was added to the selection or false if cell was removed from the selection.

I have created a Java application that lets you experiment with selecting cells and viewing the results of your selections. Check out Listing 3 for that application’s source code.

Listing 3 SampleGraph3.java

// SampleGraph3.java

import org.jgraph.JGraph;
import org.jgraph.event.*;

import javax.swing.*;

public class SampleGraph3 extends JFrame
  public SampleGraph3 (String title)
   super (title);

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   JGraph graph = new JGraph ();

   GraphSelectionListener gsl;
   gsl = new GraphSelectionListener ()
        public void valueChanged (GraphSelectionEvent gse)
          Object [] cells = gse.getCells ();
          for (int i = 0; i < cells.length; i++)
            System.out.println (cells [i] + ": " +
                      (gse.isAddedCell (cells [i]) ?
                               "added" :
   graph.addGraphSelectionListener (gsl);

   getContentPane ().add (new JScrollPane (graph));

   pack ();

   setVisible (true);

  public static void main (String [] args)
   new SampleGraph3 ("Sample Graph 3");

After compiling Listing 3 and running the application, perform a marquee selection of the JComponent vertex, the extends edge, and the JGraph vertex. You should see the following output:

JComponent: added
JGraph: added
extends: added

Three cells have been added to the selection since the previous selection (in which there were no cells). Press Ctrl and deselect JGraph. In response, you will see one more output line consisting of JGraph: removed. Deselecting this cell is the only change that has occurred since the last selection.

Perhaps you are not interested in the relative changes that have taken place from one selection to another, but would rather identify all cells within the selection. You can easily obtain this information from within the event handler, as the following code fragment demonstrates:

public void valueChanged (GraphSelectionEvent gse)
  JGraph g = (JGraph) gse.getSource ();
  GraphSelectionModel gsm = g.getSelectionModel ();

  // Obtain and output all selected cells.

  Object [] cells = gsm.getSelectionCells ();
  for (int i = 0; i < cells.length; i++)
    System.out.println (cells [i]);

Graph View and Cell Views

Along with the graph and selection models, each JGraph object references the graph view, a view of the entire graph. This view is implemented by the org.jgraph.graph.GraphLayoutCache class. Various JGraph constructors take a GraphLayoutCache argument to specify the graph view when the JGraph component is created. If you invoke a JGraph constructor that does not take a GraphLayoutCache argument (such as the no-argument constructor), the graph view is created behind the scenes as a GraphLayoutCache instance.

GraphLayoutCache implements the org.jgraph.graph.CellMapper interface. This interface describes methods for mapping each of a model’s cells to a corresponding cell view, a view of a single cell, and returning (and possibly creating) cell views. The cell view provides a renderer for painting the cell, an editor for in-place editing, and a handle for more sophisticated editing. The renderer is shared among all instances of a specific cell view. The editor and handle are created on the fly.

Cell views are implemented by classes that implement the org.jgraph.graph.CellView interface. The org.jgraph.graph.AbstractCellView class provides a partial implementation of a cell view. Because vertices, edges, and ports have varying appearances and editing requirements, a complete implementation of a cell view is deferred to the org.jgraph.graph.VertexView, org.jgraph.graph.EdgeView, and org.jgraph.graph.PortView classes.

One of the arguments passed to most GraphLayoutCache constructors is an object whose class implements the org.jgraph.graph.CellViewFactory interface, such as org.jgraph.graph.DefaultCellViewFactory. Whenever GraphLayoutCache needs to map a model cell to a cell view, it calls CellMapper’s public CellView getMapping(Object cell, boolean create) method with true as the value of create. In turn, getMapping() invokes one of the factory’s methods to create the cell view. The method that gets called depends on whether the cell is a vertex, an edge, or a port. When the method creates a cell view, it also creates dependent cell views. For example, when confronted with a vertex that has a dependent port, the factory method creates the vertex view and the dependent port view.

You can override the current graph view by invoking JGraph’s public void setGraphLayoutCache(GraphLayoutCache newLayoutCache) method. To obtain the graph view currently being used, invoke JGraph’s public GraphLayoutCache getGraphLayoutCache() method. For example, the following code fragment (excerpted from HelloWorld.java) invokes getGraphLayoutCache() to return the graph view and then invokes GraphLayoutCache’s public void insert(Object [] cells) method to insert the cells specified by the cells array into the graph model:

graph.getGraphLayoutCache ().insert (cells);

In addition to updating the graph model, insert() ultimately updates the graph view and affected cell views (and even creates new cell views, as necessary).

UI Delegate

Figure 1 reveals the org.jgraph.plaf.GraphUI abstract class and its concrete org.jgraph.plaf.basic.BasicGraphUI subclass. Collectively, those classes describe JGraph’s UI delegate.

The UI delegate has lots of work to do: Detecting changes to the graph model or graph selection model and responding appropriately, painting the graph view and cell views, and taking care of in-place editing and cell handling are some of its tasks.

Although you might not care about the inner workings of the UI delegate, our exploration of JGraph’s architecture would not be complete without an examination of this essential entity. Also, an understanding of how the UI delegate works is necessary should you wish to extend the JGraph component with new capabilities. For brevity, we will only examine a code fragment excerpted from BasicGraphUI’s public void paint(Graphics g, JComponent c) method—the entry point for painting the graph view and cell views. The code fragment in question paints the cell views:

// Paint cells

CellView [] views = graphLayoutCache.getRoots ();
for (int i = 0; i < views.length; i++) 
   Rectangle2D bounds = views [i].getBounds ();
   if (bounds != null "" real != null "" bounds.intersects (real))
     paintCell (g, views [i], bounds, false);

GraphLayoutCache provides a public CellView [] getRoots() method that returns an array of root cell views from its own internal list of these views. For each root cell view, that view’s rectangular boundaries are retrieved. If these boundaries lie within the viewable area of the graph (scaling is taken into account, hence the two occurrences of real), the root cell view followed by its children cell views are painted, by invoking the paintCell() method.

  • + Share This
  • 🔖 Save To Your Account