Home > Articles > Programming > Java

Tools of the Trade, Part 2: Building Graphs with JGraph

Graphs are combinations of vertices and edges representing networks of related and (typically interconnected) objects. Examples include roads, molecules, and even the Internet. Although the graph concept is easy to understand, creating the software to build, display, and manipulate graphs is not so easy. But there's good news: The open-source JGraph tool overcomes that difficulty. This article by Jeff Friesen, the second in a three-part series exploring useful open-source tools, introduces you to JGraph. After showing you how to acquire, install, and configure JGraph, you'll be able to create a simple Java application that creates and displays a sample graph.
Like this article? We recommend

For more information on Java development, visit our Java Reference Guide or sign up for our Java Newsletter.

Last time, I introduced you to a series on useful open-source tools that could prove beneficial to your Java career. The inaugural article focused on iText, an open-source Java library for creating PDF, HTML, RTF, and XML documents. This article continues the series by presenting JGraph.

Computer science defines a graph as a nonempty finite set of vertices (labelled points) and a set of edges (pairs of vertices) that signify connections between the vertices. Graphs represent networks of related and (typically) interconnected objects such as roads, molecules, database schemas, and the Internet. Although the graph concept is easy to understand, creating the software to construct, display, and manipulate graphs can be difficult. Thanks to Java and a utility called JGraph, you do not need to create your own graph software.

This article introduces you to JGraph. After showing you how to acquire JGraph, install this tool, and set the CLASSPATH environment variable, I present a simple Java application that uses JGraph to create and display a sample graph. This application introduces you to several operations that JGraph provides for graph manipulation. The article then explores several important areas of JGraph’s architecture. This JGraph overview provides you with enough knowledge to quickly start creating your own graphs.

JGraph Intro

JGraph, created by Gaudenz Alder, is an open-source, Swing-based component for building, displaying, and manipulating graphs. JGraph is available as a free version under the GNU Lesser General Public License (LGPL) and as a commercial version under the JGraph General License. The main difference between these licenses: LGPL requires you to include JGraph’s source code (including any modifications you make to JGraph) when distributing an application that uses JGraph; JGraph’s source code does not need to be included under the General License.

Visit the JGraph Free Downloads page to download the binary and source distributions for the latest free version of JGraph. You need only the binary distribution for this article: Click the Download Latest Binary Distribution link to obtain that distribution. After the download finishes, you will discover jgraph-latest-lgpl.jar on your hard drive.

From the command line, invoke java -jar jgraph-latest-lgpl.jar to install JGraph. After agreeing to all terms in the license agreement, choose an installation directory, such as c:\jgraph (which is the installation directory assumed in this article). JGraph installs to this directory. If installation is successful, the installation directory will contain the following files and directories:

  • ChangeLog identifies those changes introduced by each version of JGraph.
  • LICENSE presents version 2.1 of the LGPL.
  • README introduces JGraph and provides instructions for building this tool from its source code.
  • WHATSNEW describes new features and bug fixes introduced by each JGraph version. This file’s content is similar to the content found in ChangeLog.
  • doc provides JGraph documentation. Its api subdirectory contains Javadoc files that describe the API. The pdf subdirectory contains an updating.pdf file with information that can help you update existing JGraph code to the latest version.
  • examples provides a package of Java programs that demonstrate JGraph features.
  • lib provides the jgraph.jar Jar file, which you must add to your CLASSPATH environment variable before you can use JGraph. For Windows 98 SE, the command to set CLASSPATH is set classpath=%classpath%;c:\jgraph\lib\jgraph.jar;. If you are using a different version of Windows, or a non-Windows operating system, study your OS documentation to find out how to set this environment variable.

Now that JGraph has been downloaded, installed, and configured, we can explore a Java application that uses JGraph to create a sample graph. Take a look at Listing 1.

Listing 1 SampleGraph.java

// SampleGraph.java

import org.jgraph.JGraph;

import javax.swing.*;

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

   setDefaultCloseOperation (EXIT_ON_CLOSE);

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

   pack ();

   setVisible (true);

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

Listing 1 describes a Swing application that introduces a sample graph into its GUI. The application’s constructor introduces the sample graph by creating an org.jgraph.JGraph object and invoking its public JGraph() constructor to initialize this object. The JGraph object is then placed into a JScrollPane (to make sure that the entire graph is viewable, even when the graph exceeds its display area because the window has been resized smaller) and the JScrollPane is added to the JFrame’s content pane.

After compiling Listing 1, run this application. You will see the sample graph that is presented in Figure 1. The rectangles serve as the graph’s vertices, and the lines serve as its edges.

Figure 1

Figure 1 The sample graph reveals JGraph component architecture.

Figure 1’s sample graph is not just for show: You can also manipulate this graph by performing various operations. For example, double-click the vertex that displays JComponent (or single-click that vertex to select it and then press F2). In response, an editor appears over the vertex to perform in-place editing of the vertex’s label. Type abc into that text field and then press Enter. You should now see abc instead of JComponent. Figure 2 reveals the editor and the entered label.

Figure 2

Figure 2 You can perform in-place editing on a vertex or an edge.

When you select a vertex, you will notice small handles (rectangles that you can grip for sizing) in the vertex’s corners and along its sides. Similarly, the selection of an edge results in handles at the source and target of that edge. These handles make it possible to resize the vertex or edge. Accomplish that task by using the mouse to select and drag a handle: The vertex or edge resizes in that direction. For example, resize the JGraph vertex by selecting that vertex, gripping the handle in the lower-right corner, and dragging the handle downward and to the right. Figure 3 shows this vertex expanding.

Figure 3

Figure 3 A vertex changes color during a resize operation.

You can select a combination of vertices and edges by holding down Shift during the selection process. If you accidentally select a vertex or edge that you do not want to be included, release Shift and press Ctrl to deselect that vertex/edge. A pair of selected vertices and the edge that connects those vertices are dragged to another location in Figure 4.

Figure 4

Figure 4 An edge between two selected vertices is automatically selected.

Resizing or dragging a selection—you can abort either operation by pressing Esc—is accomplished through a cell handle. In contrast to an editor that uses a text component to change a vertex/edge label through in-place editing, a cell handle uses other means (such as performing a color change and showing grayed edges in their new locations) to provide users with visual feedback on how a graph will look after the change has been made. JGraph refers to this feature as live-preview.

JGraph supports the placement of related vertices and edges into groups, a mechanism for structurally organizing a graph. The presence of groups within a graph affects the selection process. When selecting a vertex or edge within a group, the first mouse click on the vertex or edge selects the group (whose members can then be resized or dragged as a single unit—you can even edit the group’s name); the second mouse click selects the vertex/edge. (If groups are nested within other groups, it can take multiple clicks on the vertex or edge before that vertex/edge is selected.) Figure 5 illustrates this stepping into groups feature. Notice the dashed outline around a group, consisting of vertex GraphModel, edge implements, and vertex DefaultGraphModel. That outline indicates the selection of the group. Also notice the selection of the implements edge, whose label appears in the editor.

Figure 5

Figure 5 Click once for the group and twice for the edge.

You can select multiple groups, vertices, and edges by pressing Shift and clicking each entity, but that is somewhat cumbersome. If those entities exist within a rectangular area, an easier way to accomplish this task involves marquee selection.

Marquee selection is a selection mechanism in which you move the mouse pointer to any location in the graph and press a mouse button. As you drag the mouse pointer, you observe a rectangle—known as a marquee—that expands or contracts, based on the direction of movement. When you release the mouse button, the marquee disappears; all groups, vertices, and edges completely within the marquee are selected. Figure 6 reveals the marquee. When the mouse button is released, the JComponent vertex, the extends edge, and the JGraph vertex will be selected.

Figure 6

Figure 6 Select a group by including all vertices and edges within the marquee.

Sometimes, you will want to more accurately place a vertex, an edge, or a group during a drag operation—by constraining the drag to horizontal and vertical movement. In other words, you do not want to drag diagonally. JGraph provides a constrained drag operation to help you accomplish this task. That operation requires you to hold down Shift while dragging the mouse.

There is one final operation to consider: clone selection (the duplication of a vertex, an edge label, or a group by holding down the Ctrl key while dragging the mouse). Unlike constrained drag, clone selection cannot be demonstrated in SampleGraph without changing the source code. The change requires replacing the following line of code:

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

with this code fragment:

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

Modify SampleGraph.java to incorporate the code fragment above, compile the source code, and run the application. Position the mouse pointer over a vertex, an edge label, or a group member and then hold down Ctrl while dragging the mouse. You will end up with a clone of the vertex, edge label, or group.

For more practice with JGraph’s operations, you will want to check out the graph editor example that ships with JGraph. Compile the graph editor’s source code, which resides in c:\jgraph\examples\org\jgraph\example\GraphEd.java, and run that program as an application—you can also run the graph editor as an applet. Figure 7 reveals the graph editor’s GUI.

Figure 7

Figure 7 The graph editor lets you create, drag, and connect vertices.

The graph editor’s toolbar presents several icons. Click the leftmost icon to introduce a vertex into the GUI. The icon immediately to the right, when it appears as an arrow, causes a small rectangle to appear in the midst of a vertex. Selecting that rectangle and dragging the mouse results in an edge being drawn from the vertex (presumably you want to draw the edge to another vertex). But if the icon appears with a stylized red X drawn on top, you cannot draw an edge.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020