A JavaScript Application for Server Load Monitoring (Continued)

We continue the ServerLoad tutorial with the diagram.

I. Create and Style The Diagram

We create a new JavaScript file named diagram.js in the Scripts folder of the project and reference it in the HTML.

<a href="http://Scripts/MindFusion.Diagramming.js">http://Scripts/MindFusion.Diagramming.js</a> 

Now, in this file we make some namespace mapping to access easy the classes we need:

var Diagram = MindFusion.Diagramming.Diagram;
var DiagramLink = MindFusion.Diagramming.DiagramLink;
var ShapeNode = MindFusion.Diagramming.ShapeNode;
var Style = MindFusion.Diagramming.Style;
var DashStyle = MindFusion.Drawing.DashStyle;
var Alignment = MindFusion.Diagramming.Alignment;

var Rect = MindFusion.Drawing.Rect;
var LayeredLayout = MindFusion.Graphs.LayeredLayout;
var LayoutDirection = MindFusion.Graphs.LayoutDirection;

// a shortcut to the Events class
var Events = MindFusion.Diagramming.Events;

The code for the diagram does not need to be in a single method call, so we’ll use the document.ready event handler:

$(document).ready(function () {

// create a Diagram component that wraps the "diagram" canvas
diagram = MindFusion.AbstractionLayer.createControl(Diagram, null, null, null, $("#diagram")[0]);
//set both base and head link shape size


As with the line chart, we create a diagram object using the canvas id from the html page. Then we make some link customization: we set the base and head shape with setBaseShape and setHeadShape to “Arrow” to indicate that data flows in two directions between servers.

Now let’s use a Style instance to set the stroke, text color and font name. Then we set the link style this way:

//customize the link appearance
var linkStyle = new Style();

When users click on the diagram it is important not to allow them to create new links and nodes. That’s why we use setBehavior to change the default way the diagram responds to user actions:

//diagram items can only be selected

We create the graph in the buildDiagram method. First, we call clearAll to remove all diagram items to make sure only nodes we’ve created are visible:

//generate diagram nodes
function buildDiagram() {


II. Diagram Items

Let’s create the diagram nodes. We use png icons we’ve saved in an “icons” folder in the website. The background of each node is transparent ( setTransparent ), which means only the image will be visible. Then we add the node to the items of the diagram:

var rect = new Rect(0, 0, 15, 15);

var node = new ShapeNode(diagram);
//the web server

We create similar nodes for the data server, the clients and the network servers. The links are created with the DiagramLink class. The constructor takes the origin and target node of the link as parameters. We set an setId to the links, which is important and we add a label :

//add a link between the client and the server
var link = new DiagramLink(
       diagram, node, diagram.nodes[0]);
//same as the title of a given chart series
link.setId("Client" + i);
link.addLabel("Client" + i);

Let’s not forget to emphasize the two links that correspond to the two series that are initially emphasized on the chart:

//bolden the two major links

III. Layout

We’ve created the diagram items but we need to arrange them. We use the LayeredLayout algorithm:

//the layeredLayout arranges the diagram properly - into layers
function applyLayeredLayout() {
    var layout = new LayeredLayout();
    layout.direction = LayoutDirection.TopToBottom;
    layout.siftingRounds = 0;
    layout.nodeDistance = 20;
    layout.layerDistance = 20;

As you see it is very easy to apply a layout with the diagramming control. You just create an instance of the layout, set the properties of your choice and call arrange (). In our case we need the layout direction to be LayoutDirection.TopToBottom We also adjust the nodeDistance and layerDistance and set the number of siftingRounds (attempts to unwind split links) to 0.

IV. Events

The diagram is meant to be interactive. We use the linkSelected and clicked events to handle selection of links and click on an area of the diagram, unoccupied by any items.

// add listeners
diagram.addEventListener(Events.linkSelected, onLinkSelected);
diagram.addEventListener(Events.clicked, onClicked);

When a link is selected, we need to emphasize the line graphic that corresponds to this link. We also emphasize the link itself. In addition, we must adjust the stroke and thickness of the other line graphs and diagram links. We do this in the onLinkSelected method:

//handle the linkSelected event
function onLinkSelected(sender, args) {

    //get the style of the series
    var seriesStyle = lineChart.plot.seriesStyle;

    //thicken just the selected series, the others should be transparent
    for (var j = 0; j &lt; lineChart.series.count() ; j++) {

First we get the series style and then we use setStrokeThickness to reset the thickness of diagram links and series to their default values. After we’ve done that we need to get the selected links and emphasize them:

//bolden all selected links in the diagram as well
for (var m = 0; m &lt; diagram.selection.links.length; m++) {
     var clickedLinkId = diagram.selection.links[m].getId();

When we’ve done that we need to find the series that correspond to these links and emphasize them as well:

//find the series that correspond to the selected links
for (var i = 0; i &lt; lineChart.series.count() ; i++) {
      var _series = lineChart.series.item(i);

      //adjust the stroke thicknesses
      if (_series.title == clickedLinkId) {

          seriesStyle.strokeThicknesses.insert(i, 3);


All this is followed by a call to the draw method that repaints the chart.

//repaint the chart

The next event handler – the onClicked method resets the thicknesses to their default values:

//reset the chart thicknesses
function onClicked(sender, args) {


This is done in the resetThicknesses method, which uses the seriesStyle field of the line chart:

/* bolden the two major series, the others should be very thin.
bolden the two major diaglinks as well. */
function resetThicknesses() {
   var seriesStyle = lineChart.plot.seriesStyle;

   for (var j = 0; j &lt; 5; j++) {

V. Tyre Separators

The diagram is divided into three parts by three separator lines. These lines are unconnected DiagramLink instances that have no head and base shape and have a custom position for the label. We use absolute positioning to locate the arrows. To do this we need to know the current size of the diagram:

//add the separators for the tyres
//first get the size of the diagram
var width = diagram.getBounds().width;
var height = diagram.getBounds().height;

Then the separator link is created with both origin and destination node being null:

//separator for the Clients tyre
//the link starts from the left edge and eds to the right edge of the digram
var link = new DiagramLink(
		diagram, new MindFusion.Drawing.Point(2, (height / 3.5)),
        new MindFusion.Drawing.Point(width, (height / 3.5)));
//remove the shapes at both ends
//do not allow this link to be selected
//move the link label to the right
var linkLabel = link.addLabel("Clients");
linkLabel.setControlPointPosition(1, -5, 0);

Note that we’ve used the setLocked property of the link and have set it to true. This means the link cannot participate in user interaction – it can’t be selected, moved, resized. That’s what we want.

And with this our sample server load application is ready. Once again, here is how it looks:

Server Load Application in JavaScript

Server Load Application in JavaScript

Run The Application

Use this link to download the full sample with all necessary libraries and scripts.

Download Source Code

You can also fork it from GitHub.

Visit the web pages of the diagramming and charting (with gauges) JavaScript libraries to learn more about these tools. Visit the MindFusion forums if you need technical support or want to ask further questions about MindFusion developer tools.

A JavaScript Application for Server Load Monitoring

In two blog posts we will look at the main steps to create a sample server load web application. We will use the chart, gauge and diagram libraries. The data is simulated with random numbers.

Server Load Application in JavaScript

Server Load Application in JavaScript

Run The Application

The chart shows number of users on a given connection between two stations in the network at each moment. The graphic includes data for the last 30 seconds. The diagram shows the servers and clients that build the network. By default the charts shows data only for the two most important connections, out of total 10. Users can select different connections and view their graphics. The gauge control provides data for the average count of users at any given moment.

I. Project Setup

We create an empty website and add a Scripts folder with the necessary files:


and a reference to jQuery or the jQuery library itself:


We create a blank HTML file and we create three HTML Canvas elements – one for each of the controls: chart, diagram, gauge.

We use the Flexbox layout and we create a CSS file referenced by the index.html file where we write the CSS settings for the layout:

<link href="common/style.css" rel="stylesheet" />

We initialize a section region that would have a Flexbox layout:

section {
   display: flex;
   max-width: 700px;

The CSS class used for <div> elements inside <section>:

.column {
  margin: 10px 10px 0px 0px;
  flex: 1 1 0;
  border: 1px solid #cecece;

section:first-of-type .column:first-of-type {
  flex: 1 1 auto;

We specify that the first column on the second row would be twice wider than the other column. This is the diagram, and the other column is occupied by the gauge.

section:nth-of-type(2) .column:first-of-type {
  flex: 2 2 22;

That’s how the HTML uses the CSS attributes:

    <div class="column">
      <canvas id="lineChart"></canvas>

Note the id=”lineChart” attribute – we will use the id to initialize the LineChart object in the *.js file. The diagram and gauge Canvas instances also have id-s.

At the end of the index.html we include a reference to the require.js file to load the chart and gauge libraries this way:

<script src="Scripts/diagram.js" type="text/javascript"></script>
<script data-main="charts" src="Scripts/require.js"></script>

Note: Internet Explorer might not load properly the JavaScript libraries if they are declared at the beginning of the file, (in the head section) before the initialization of the Canvas-es. Therefore it is best to put the script references at the bottom, right before the closing </body> tag.

II. The Gauge

The code for the OvalGauge and the LineChart is in a single method:

var lineChart = null;

define(["require", "exports", 'MindFusion.Common', 'Scripts/MindFusion.Charting', 'MindFusion.Gauges'], function (require, exports, MindFusion_Common_1, m, g) {
    "use strict";

Before the method we declare a global variable for the LineChart. We need to access it in the diagram file so it must have a global visibility.

The OvalGauge control is created using the id of the HTML Canvas:

var userCounter = g.OvalGauge.create($('#userCounter')[0], false);

We will use two Events – raised before the background was painted and before the pointer was painted – to customize how the gauge background and pointer look.

//use custom painting of the background and of the pointer
userCounter.addEventListener(g.Events.prepaintBackground, onGaugerepaintBackground.bind(this));
userCounter.addEventListener(g.Events.prepaintPointer, onPrepaintPointer.bind(this));

The gauge needs a scale – we create an OvalScale and set its min and max value:

var scale = new g.OvalScale(userCounter);

We will also set all three types of settings on the scale – MajorTickSettings, MiddleTickSettings and MinorTickSettings

//initialize the major settings
var majorSettings = scale.majorTickSettings;

A CustomInterval at the MajorTickSettings indicates a special range. We will use one to paint in red the portion on the scale that corresponds to the high amount of users:

 var interval = new g.CustomInterval();

Then we customize the MajorTickSettings, the MiddleTickSettings and MinorTickSettings:

//initialize the middle settings
var middleSettings = scale.middleTickSettings;

//initalize the minor settings
var minorSettings = scale.minorTickSettings;

The scale shows a Range: that is a visual indication of regions on the gauge. It is determined by its setMinValue and setMaxValue values and in our case we will show it on the whole gauge:

//add a range in gradient colors
var range = new g.Range();
range.setFill(g.Utils.createLinearGradient(320, [1, '#ce0000', 0.8, '#ce0000', 0.7, '#FFA500', 0.6, '#FFD700', 0.5, '#008000', 0, '#008000']));

That’s how we handle the PrepaintBackground event to draw custom background for the gauge:

//paint the background in gradient
function onGaugerepaintBackground(sender, args) {
   var context = args.getContext();
   var element = args.getElement();
   var size = sender.getSize();
   var ellipse = new g.Ellipse();
   args.paintVisualElement(ellipse, size);
   var ellipse = new g.Ellipse();
   ellipse.setFill(g.Utils.createLinearGradient(300, [0, '#808080', 0.2, '#808080', 0.8, '#909090', 1, '#909090']));
   ellipse.setMargin(new g.Thickness(0.015));
   args.paintVisualElement(ellipse, size);

The code that handles the prepaint pointer event is similar. The value of the Pointer is set this way:

//add some initial value

When the last chart values changes – each second – we update the pointer value:

var pointer = userCounter.scales[0].pointers[0];

III. The Chart

First we create the LineChart object from the Canvas that we have initialized in the HTML. We take the width and height of the control from its parent container:

var lineChartEl = document.getElementById('lineChart');
lineChartEl.width = lineChartEl.offsetParent.clientWidth;
lineChartEl.height = lineChartEl.offsetParent.clientHeight;
lineChart = new Controls.LineChart(lineChartEl);

The data for the line series is stored in 10 Series2D instances. For each of them we need a list with the X and Y values. The X-values are the same for all series, the Y-values are randomly generated numbers. All of them are instances of the List class:

var values1 = new Collections.List();
var values2 = new Collections.List();
var xValues = new Collections.List();
var xLabels = new Collections.List();

Here we fill the xValues list with numbers:

//initialize x-values and labels, generate sample data for the series
for (var i = 0; i &lt; 30; i++) {

The setXLabels method takes care of the custom labels at the X-axis. At each 3rd call, it removes the first three values and adds three new ones: one with the current time stamp and two more as empty strings.

if (d.getSeconds() % 3 == 0)
     //clear the first three values
     //if the count of the labels is more than 30
     if (removeFirst) {

       //add a label and two empty strings
       xLabels.add(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());

We create the Series2D instances and add them to the Series property of the line chart:

//the series for the chart
var series = new Collections.ObservableCollection(new Array(
    new Charting.Series2D(xValues, values1, xLabels),
    new Charting.Series2D(xValues, values2, null),
    new Charting.Series2D(xValues, values10, null)));

The xLables are assigned just to the first series, they will serve as labels source for the X-axis.To show them, we must first hide the coordinates and assign them to the xAxis:

lineChart.xAxis.labels = xLabels;
lineChart.showXCoordinates = false;

then we must “tell” the first series that its labels are used for the XAxis:

//tell the series that the labels are for the X-axis.
series.item(0).supportedLabels = m.MindFusion.Charting.LabelKinds.XAxisLabel;

We use the title property of a Series object to identify the series. That’s why we assign to them unique labels:

//series titles are important - we identify the series with them
for (var i = 0; i < 4; i++)
    series.item(i).title = "Client" + i;

for (var i = 0; i < 3; i++)
    series.item(i + 4).title ="Network" + i;

for (var i = 0; i < 3; i++)
    series.item(i + 7).title ="Data" + i;

Since it is going to be a long chart, we want a second Y-axis to appear to the right. That can be done by adding another YAxisRenderer with the same yAxis to the components rendered by default by the LineChart control. We add the new YAxisRenderer to a vertical StackPanel:

 var y2Stack = new m.MindFusion.Charting.Components.StackPanel();
 y2Stack.orientation = m.MindFusion.Charting.Components.Orientation.Vertical;
 y2Stack.gridRow = 0;
 //add the stack panel to the last grid column
 y2Stack.gridColumn = lineChart.chartPanel.columns.count() - 1;


The layout manager for a LineChart is a Grid panel. We add a new column to it, where the second Y-axis will be rendered. Then we add the StackPanel with the YAxisRenderer to this column. Next we add the yAxis and we specify that the plot is not to the left side of it:

//create the second Y-axis
var secondYAxis = new Charting.YAxisRenderer(lineChart.yAxis);
secondYAxis.plotLeftSide = false;

Then we customize the grid and trigger the timer that will update the data values at each second:

lineChart.gridType = Charting.GridType.Crossed;
lineChart.backColor = new Drawing.Color.fromArgb(230, 230, 230);
lineChart.theme.gridColor1 = Drawing.Color.fromArgb(1, 255, 255, 255);
lineChart.theme.gridColor2 = Drawing.Color.fromArgb(1, 255, 255, 255);
lineChart.theme.gridLineColor = Drawing.Color.fromArgb(0.5, 240, 240, 240);
//start the timer
setInterval(setTime, 1000);

Finally, let’s look at the styling of the series. We keep the brushes in a list. The colors for those brushes are stored in a list with lists – each one with three elements for the red, green and blue values of the color.

//the colors for the brushes
var brushes = new Collections.List();

var rgbColors = new Collections.List();
rgbColors.add(new Array(102, 154, 204));

What we actually do to show the graphics of the connections that are selected in the diagram is thicken the strokes for those line graphics and set the thickness to the rest to 0.15 to make them barely visible.

We do that by using the thicknesses property of the PerSeriesStyle class that we use for styling the chart.

lineChart.plot.seriesStyle = new Charting.PerSeriesStyle(brushes, brushes, thicknesses);

And here is how we create the thicknesses and the brushes:

//create brushes for the chart
var thicknesses = new Collections.List();
  for (var i = 0; i < 10; i++)
      var a = rgbColors.item(i);
      brushes.add(new Drawing.Brush(new Drawing.Color.fromArgb(a[0], a[1], a[2])));
      if (i == 5 || i == 8)

Only the 5th and 8th thickness are set to 3, the others are almost zero – enough to draw the silhouettes of the graphics.

And that’s all for this part I of the tutorial on how to build the client side of a sample server load monitor application in JavaScript. In part II we will look at the diagram control. You can run the sample from here:

Run the online server load monitor application

Here is the link to download the full source code for the application:

Download Source Code

You can also fork it from GitHub.

Find out more about the chart, gauge and diagram JavaScript libraries from their official pages on the MindFusion website.

Ticket Booking System (Continued)

In part I of the Ticket Booking System blog post we discussed the controls used in the software and how we generate and arrange the hall seats. Now let’s get deeper into the details on how we retrieve the data and how we customize the controls.

We use the Entity Framework and the Entity Data Model wizard to connect to our MS SQL database and retrieve the ticket data. Here is the model of the database:

Event Booking Software: MS SQL Database Model

Event Booking Software: MS SQL Database Model

I. The Database

We have a table for the event type (ballet, concert, opera etc.), a table for the events (Swan Lake ballet, Mozart concert, La Traviata oepra etc.), a table for the performances (an event with a date) and a table for the tickets that were sold. The performance table has a column for the base price of the tickets. The hall is divided into 3 sections according to the price of the tickets – the Performance table stores the price for the cheapest category. The other two categories are calculated according to the base price.

II. Events

We keep a class variable for the EventsTicketsEntities, which we initialize in the Form1 constructor:

public partial class Form1 : Form
   EventsTicketsEntities records;
   double basePrice;

   public Form1()
      records = new EventsTicketsEntities();

The events are instances of the Appointment class of the Calendar. Here is the method that we use to create the Appointment-s based on the data from the database:

private void loadEvents()

  List performances = records.Performances.ToList();     

  foreach (Performance p in performances)
      Appointment app = new Appointment();
      app.StartTime = (DateTime)p.Date;
      app.EndTime = app.StartTime.AddHours(2.0);           
      app.HeaderText = "";
      app.DescriptionText = p.Event.Title;
      app.Tag = p.Event.EventType_Id;
      app.Style.Brush = getBrush((int)app.Tag);


We read all records in the Performances table and create an Appointment for each one. The start date of the event is the field from the database. We add to it 2 hours as duration, otherwise the event wouldn’t show up. The brush of the Appointment depends on the type of the event. The appointment does not show any text, but the event title serves as a description. As a rule the calendar control renders an Appointment‘s description as a tooltip when the user hovers the item.

The schedule item description is rendered as a tooltip

The schedule item description is rendered as a tooltip

III. Hall Seats

In order to identify the location of a seat we assign an instance of the Seat structure as an Id to the ShapeNode that represents the seat.

public struct Seat
  public Seat (int row, int column)
     this.Row = row;
     this.Place = column;

  public int Row
     get; set; 

 public int Place
       get; set;


We also include a rowStart parameter in the CreateSection method. The parameter keeps track of the total count of seats being generated. This allows each seat to have a unique row number:


void CreateSection(int rowStart, int[] seatsPerRow,
    float topY, float seatWidth, float seatHeight,
     float xPadding, float yPadding, float arcRadius)
        seat.Id = new Seat(rowStart + r, s);
        seat.Tag = calcSeatCoeff((Seat)seat.Id);	


The Seat tag of the ShapeNode is calculated based on its location in the hall. It is the coefficient, which multiplied by the base price for this performance gives us the final price for this seat.

Each time a new performance is selected on the calendar, our application must refresh the seat info. Here is the method that takes care of the seat colors:

//clears the X sign at an occupied seat
private void updateSeats( double basePrice )
  foreach( var seat in diagram.Nodes)
     (seat as ShapeNode).Text = "";
     if (seat.Tag != null)
        seat.Brush = getSeatBrush(basePrice * (double)seat.Tag);

The method calculates the price of the seat and checks the color that corresponds to this price. Whenever a seat is clicked, the application marks it as selected. This is done by drawing an “X” as text on the ShapeNode using a large Font size:

Seat seatInfo = (Seat)seat.Id;
TICKETS_SOLD _ticket = new TICKETS_SOLD() { };
_ticket.Id = records.TICKETS_SOLD.ToList().Count;
_ticket.Performance_Id = (int)calendar.Tag;
_ticket.Row_Index = seatInfo.Row;
_ticket.Seat_Index = seatInfo.Place;

catch (DbEntityValidationException ex)
    seat.Text = "X";

We create a new TICKETS_SOLD record, which contains a unique Id for the sold ticket, an Id for the performance, and the location of the seat (row and column). There is something more to that. When the user tries to click on a seat that is already sold we want to warn him that it is not possible to buy the seat. This is done by having a special node that stays hidden and shows up for a few seconds only to warn the user:

private void generateOccupiedNode()
    float x = diagram.Bounds.Left + diagram.Bounds.Width / 2 - 50;
    float y = diagram.Bounds.Top + diagram.Bounds.Height / 2 - 30;

    RectangleF nodeBounds = new RectangleF(x, y, 100, 60);
    ShapeNode node = diagram.Factory.CreateShapeNode(nodeBounds);
    node.Brush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(100, 206, 0, 0));            
    node.Font = new Font("Arial", 26);
    node.TextBrush = new MindFusion.Drawing.SolidBrush(Color.Black);
    node.Visible = false;
    node.Shape = Shapes.RoundRect;
    node.Id = "Occupied";


The seat is rendered in the middle of the diagram’s visible area and has a semi – transparent background. We use a timer to track the seconds when the node is displayed:

private void diagram_NodeClicked(object sender, NodeEventArgs e)
   ShapeNode seat = e.Node as ShapeNode;
   if(seat != null)
       if(seat.Text == "X")
           ShapeNode warning = (ShapeNode)diagram.FindNodeById("Occupied");

          if(warning != null)
             warning.Text = "This Seat is Occupied!";
             Timer timer = new Timer();
             timer.Interval = 2500;
             timer.Tick += Timer_Tick;
             warning.Visible = true;

We then find the node and make it invisible again:

private void Timer_Tick(object sender, EventArgs e)
    ShapeNode warning = (ShapeNode)diagram.FindNodeById("Occupied");
    warning.Visible = false;

With this we have covered the basic methods that build the Event Ticket Reservation Software. Here is the final version:

Event Booking System in WinForms

Event Booking System in WinForms

The full source code of the application together with the sample database is available for direct download from here:

Event Ticket Booking System – Download

The sample uses the Diagramming and Scheduling controls from the MindFusion WinForms Pack. If you have questions regarding the sample or the components do not hesitate to post them on the MindFusion discussion board.

A Poll Chart: A Stacked Bar Chart in Java Swing that Represents Results of a Survey – II

Here is a link to Part I: Overview of chart elements, the dashboard, plot and axes.

I. Bars Rendering

The bar graphics is rendered by a BarStackRenderer. It requires a collection of Series and we add four:

private ObservableList createSeries()
      // Important series
	BarSeries series1 = new BarSeries(
	Arrays.asList(40.0, 30.0, 52.0, 62.0),
	Arrays.asList("20%", "15%", "26%", "31%"),
	null /* no top labels */);


Each BarSeries has a list with the data, a list with the inner labels and no top labels. The BarStackRenderer renders in a single bar the values from the same index in each BarSeries e.g. the first bar renders the first double value in all BarSeries, the second bar renders the values on the second position in the series and so on. The BarRenderer itself has a few customizations:

barRenderer = new BarStackRenderer (createSeries());

Let’s not forget to add it to the Plot2D:



II. The Annotations

The labels at the X and Y axis are actually annotations – they are created by AnnotationRenderer instances. An AnnotationRenderer needs a collection of Series. For the Y-axis we use a SimpleSeries instance, which is created and used for the annotations and does not provide data for the bars:

private ObservableList createAxisLabels()
   return FXCollections.observableList(Arrays.asList(
	new SimpleSeries(null, null)
        	public String getLabel(int index, LabelKinds kind)
			return axisLabels[index];
		public double getValue(int index, int dimension) { return index; }
		public int getSize() { return axisLabels.length; }

		public int getDimensions() { return 1; }

		public EnumSet getSupportedLabels() {
	        	return EnumSet.of(LabelKinds.YAxisLabel);
		final String[] axisLabels = {
			"Accomodation", "University\nLocation", "Tuition\nPrice", "Quality of\nEducation" };

Here we indicate that this SimpleSeries provides labels for the YAxis with the getSupportedLabels override, which in our case returns LabelKinds.YAxisLabel. The label is returned by the getLabel method.

The annotations on the X-axis are rendered by a special class called CustomBarSeries. We implement the Series interface to return a set of predefined labels for each data value in this series:

public CustomBarSeries(List values, List innerLabels, List topLabels) {
	super(values, innerLabels, topLabels);
	this._values = values;
	double sum = 0;
	_stackedValues = new ArrayList(values.size());
	for(double val : values)
	   sum += val;
	this._innerLabels = innerLabels;

We also take into consideration that the values rendered by the bar chart where this class is used are stacked – so we sum them and return the summed value when asked:

public double getValue(int index, int dimension) { 
	if( dimension == 0)
	  return _stackedValues.get(index);
        return _values.get(index);			

Then we return the predefined label at the given position and :

public String getLabel(int index, LabelKinds kind)
		return _innerLabels.get(index);

	//else return the labels
	return axisLabels[index];
       final String[] axisLabels = {
		"Very Important", 
		"Somewhat\nImportant", "Slightly\nImportant", 
		"Not\nImportant" };

We create an instance of this CustomBarSeries and we assign it to the new AnnotationRenderer, that is responsible for the labels at the X-axis:

List sl = new ArrayList();
	sl.add(new CustomBarSeries(
	        Arrays.asList(25.0, 50.0, 50.0, 50.0),
	javafx.collections.ObservableList olss = FXCollections.observableList(sl);
	annotationRenderer1 = new AnnotationRenderer(olss);

Let’s not forget to bind the AnnotationRenderer to the X-axis:


Here is the final chart:

A stacked bar chart in Java Swing

Poll chart in Java Swing

That’s the end of this tutorial. Here is the link to download the full sample.

Download The Stacked Bar Chart in Java Sample

About Charting for Java: MindFusion.Charting for Java Swing is a multipurpose graphics library that lets you create and customize a large variety of chart types: bar, column, pie, doughnut, radar, polar etc., candlestick financial charts, gauges and dashboards with dynamic layout of their components. The library boasts a smart API which lets you combine and arrange multiple lots, axes, legends, images and other chart components. The chart appearance can be customized on multiple levels – from properties applied on a single element to global themes reused by all charts and series. Charts use a uniform Series interface for reading data and labels. You can implement the interface and create custom Series that matches your data source. Written in pure Java, this tool provides every type of Java Swing application with powerful charting capabilities. Read more about the component from here.

Ticket Booking System

In this blog post we will create a sample ticketing software that will allow users to select events and book tickets for them. We will use the MindFusion Diagramming and Scheduling components for WinForms. The tutorial is divided int two parts:

I. The Controls

We create a WinForms application in VisualStudio and add a new folder ‘Assemblies’ with the dll-s that we want to use. There we copy:

  • MindFusion.Common.dll
  • MindFusion.Common.WinForms.dll
  • MindFusion.Diagramming.dll
  • MindFusion.Diagramming.WinForms.dll
  • MindFusion.Licensing.dll
  • MindFusion.Scheduling.dll

Then we click on the Toolbox pane -> Choose Items -> Browse and we add the MindFusion.Diagramming.WinForms and MindFusion.Scheduling dll-s. They add a list of components, but we select the DiagramView and the Calendar controls and drop them onto the form. The DiagramView creates automatically the diagram instance that it renders.

II. The Hall Layout

The hall layout is rendered by the flowchart control. We use a special method that we’ve named CreateSection to create and arrange a section in the hall. The declaration of the method is:

void CreateSection(int[] seatsPerRow,
            float topY, float seatWidth, float seatHeight,
            float xPadding, float yPadding, float arcRadius)

We provide the method with an array of integers that indicate the number of seats on each row in the section. Then is the offset to the top and the size of each seat. The xPadding and yPadding arguments indicate the space between two adjacent seats. The last argument indicates how curved the row of seats is.

What the method generally does is calculate the location of each seat and generate a node with these coordinates and given size:

 float y = topY;
     for (int r = seatsPerRow.Length - 1; r &gt;= 0; r--)
           var c = new PointF(0, y + arcRadius);
           int seats = seatsPerRow[r];
           float rowWidth = seats * seatWidth + (seats - 1) * xPadding;
           float x = -rowWidth / 2;
           for (int s = 0; s  0)
                     float angle = 0;
                     float radius = 0;
                         c, new PointF(x, y), ref angle, ref radius);
                     adjustedY = c.Y - arcRadius * Math.Sin(angle * Math.PI / 180);
                     x, (float)adjustedY, seatWidth, seatHeight);
                     x += seatWidth + xPadding;
               y += seatHeight + yPadding;

The nodes are created with Factory.CreateShapeNode method which uses the Factory helper class of the diagram component. The CreateShapeNode method creates and adds the newly created nodes to the Nodes collection of the diagram.

III. The Calendar

The default settings of the Scheduling control give us exactly the month view with events we want to get. However we still need to add some customizations:

First, we won’t allow users to perform in-place edit of events on the calendar:

calendar.AllowInplaceEdit = false;

Then we will change the brushes for the calendar items and will hide the clock icons that appear at the header of events:

calendar.ItemSettings.Size = 10;            
calendar.ItemSettings.ShowClocks = MindFusion.Scheduling.WinForms.ShowClocks.Never;
calendar.ItemSettings.Style.Brush = new MindFusion.Drawing.SolidBrush (Color.FromArgb(102, 154, 204));
calendar.ItemSettings.Style.BorderBottomColor = calendar.ItemSettings.Style.BorderLeftColor =
                calendar.ItemSettings.Style.BorderRightColor = calendar.ItemSettings.Style.BorderTopColor = Color.FromArgb(192, 192, 192);
calendar.ItemSettings.SelectedItemStyle.Brush = new MindFusion.Drawing.SolidBrush (Color.FromArgb(206, 0, 0));
calendar.Selection.SelectedElementsStyle.Brush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(224, 233, 233));

Now let’s create a few items:

Appointment event1 = new Appointment();
event1.StartTime = new DateTime(2017, 5, 2, 16, 0, 0);
event1.EndTime = new DateTime(2017, 5, 2, 18, 30, 0);
event1.HeaderText = "";
event1.DescriptionText = "Swan Lake";
event1.Tag = EventType.Ballet;
event1.Style.Brush = new MindFusion.Drawing.SolidBrush(Color.FromArgb(102, 154, 204));


Our Appointment-s have a start and end time, description, brush according to the EventType and tag that indicates the type of event that is rendered. It would be nice to have tooltips that provide details about the event:

calendar.ShowToolTips = true;

This turns on tooltips on all calendar items. We want tooltips just on our events so we use the TooltipDisplaying event to hide the tooltips on items that are not events:

calendar.TooltipDisplaying += Calendar_TooltipDisplaying;


private void Calendar_TooltipDisplaying(object sender, MindFusion.Scheduling.WinForms.TooltipEventArgs e)
  if(e.Element.GetType() != typeof(Appointment))
       e.Tooltip = "";

Here is a screenshot of the event ticketing system so far:

Event Ticket System with MindFusion WinForms Controls

Event Ticket System with MindFusion WinForms Controls

A download of the project with all necessary dll-s is available from this link:

Ticket Booking System in WinForms

The Scheduling for WinForms and Diagramming for WinForms components are part of MindFusion WinForms control suite – the perfect set of tools to help you build any type of WinForms software fast and easy. Find out more about MindFusion WinForms pack here.

A Poll Chart: A Stacked Bar Chart in Java Swing that Represents Results of a Survey

Part I: Overview of chart elements, the dashboard, plot and axes.

Part II : Bar series and their drawing, rendering of custom labels with AnnotationRenderer-s.

In this blog post we will build a horizontal stacked bar chart in Java. To build the chart we use the Java chart library. We want to add a few custom elements to the chart and that’s why we will use the Dashboard control that gives us complete control over the chart elements that we use and how to arrange them.

I. Chart Elements

We use the following chart elements:

The image below gives you a visual presentation on how the components used are arranged:

The chart elements that build this stacked bar chart

The chart elements that build this stacked bar chart

The GridPanel has two rows and two columns. On the first row is the XAxisRenderer , that renders the X-axis, on the second row is the YAxisRenderer and the Plot with the BarStackRenderer .

II. The Dashboard

First, we create the Dashboard and add some styling to it with a Theme . The Theme class allows us to specify all appearance settings of a chart. We set only those that we want to use: the grid, the font:

Dashboard board = new Dashboard();
// set up appearance
Theme theme = board.getTheme();
theme.setTitleBrush(new SolidBrush(Color.black));
theme.setGridColor2(new Color(240, 240, 240));
theme.setGridLineColor(new Color(255, 255, 255));

We add the TextComponent for the title and the GridPanel to the LayoutPanel of the Dashboard . The LayoutPanel is a vertical StackPanel and it arranges the elements exactly as we want them to appear:


getContentPane().setLayout(new BorderLayout());
getContentPane().add(board, BorderLayout.CENTER);

We make sure the ContentPane of the JFrame that our Swing application uses applies the BorderLayout on the Dashboard and places it in the center which means it will stretch automatically when the user changes the size of the JFrame.

III. The Plot

The plot for the Chart is a Plot2D control. It will hold the BarRenderer and the two AnnotationRenderer -s. First, we set some general options: that the plot allows span, that it stretches in both directions and it will render a vertical grid.

//create the Plot2D
Plot2D out = new Plot2D();	

Then we go on with the styling options. The colors for the bars are set by a SeriesStyle class. We use an instance of the PerSeriesStyle which assings one brush and one fill for all elements in a single Series. We also set the HighlightStroke, which is the Brush that is used to highlight the bar that is selected:

List fills = fill();
List strokes = stroke();
out.setBackground(new SolidBrush(Color.white));
out.setSeriesStyle(new PerSeriesStyle(fills, strokes, Arrays.asList(5.0), null));		
out.setHighlightStroke(new SolidBrush(new Color(0, 0, 99)));

Finally we indicate the location of the plot in the GridPanel (more about the grid later):

//position in the grid

IV. Axes

The axes are two – X and Y. The Y axis is present, but not visible. The X-axis is visible, aligned to the top and does not draw labels. The Axis are instances of the Axis class. They both use AxisRenderer instances to be drawn:

xAxis = new Axis();

The intervals of the axis are important because they determine the location of the grid stripes. The Axis sets some apperance properties like brush and font for the labels.

//the xAxisRenderer is bound to the xAxis
xAxisRenderer = new XAxisRenderer(xAxis);			
xAxisRenderer.setAxisStroke(new SolidBrush(Colors.Black));
xAxisRenderer.setLabelBrush(new SolidBrush(Colors.Black));

Then comes the importnat part: we must tell this Axis that its labels come from an AnnotationRenderer , that it must not draw its intervals and that the labels are drawn above, rather than below the axis line:

//axis labels will be rendered by an AnnotationRenderer

Finally, we specify its location and stretch settings:

//stretch this horizontal axis
//position in the Grid

The Y-axis is similar to the X-axis, so we won’t describe its settings here. Here is the final chart:

A stacked bar chart in Java Swing

Poll chart in Java Swing

This is the end of the Part I of this tutorial. In part II we’ll cover the BarRenderer with the BarSeries and the AnnotationRenderer-s. We will also briefly discuss the GridPanel.

You can download the complete source code of the sample from here:

Download The Stacked Bar Chart in Java Sample

About Charting for Java: MindFusion.Charting for Java Swing is a multipurpose graphics library that lets you create and customize a large variety of chart types: bar, column, pie, doughnut, radar, polar etc., candlestick financial charts, gauges and dashboards with dynamic layout of their components. The library boasts a smart API which lets you combine and arrange multiple lots, axes, legends, images and other chart components. The chart appearance can be customized on multiple levels – from properties applied on a single element to global themes reused by all charts and series. Charts use a uniform Series interface for reading data and labels. You can implement the interface and create custom Series that matches your data source. Written in pure Java, this tool provides every type of Java Swing application with powerful charting capabilities. Read more about the component from here.

A Funnel Chart in JavaScript

In this blog post we will create a funnel chart that demonstrates education enrollment. We will use the JavaScript chart library.

I. Chart Setup.

The Charting library requires a few JavaScript files, which we copy in a folder named Scripts. The files are:

  • config.js
  • MindFusion.Charting.js
  • MindFusion.Common.js
  • MindFusion.Gauges.js
  • require.js

Those files are redistributed with the chart library. If you plan to use different directory structure in your project you must edit the config.js file.

Now we create two files – an HTML page FunnelChart.html and a funnelchart.js file, which will contain the code for the chart. In the FunnelChart.html file we add two references:

<script type="text/javascript" src="Scripts/config.js"></script>
<script data-main="funnelchart" src="Scripts/require.js"></script>

One to the config file and the other to the require.js file. Note that the data-main attribute points exactly to the name of the javascript code-behind file that we’ll use to create and customize the chart.

II. Create the Chart

The chart needs a canvas and we add one to the web page:

<canvas id="funnelChart" width="400" height="500"></canvas>

The size determines the size of the chart, the id is important because we’ll use it to access the canvas from code.

The code for each JavaScript chart is in a single method:

define(["require", "exports", 'MindFusion.Charting'], function (require, exports, m) {
    "use strict";
    var Charting = m.MindFusion.Charting;
    var Controls = m.MindFusion.Charting.Controls;
    var Collections = m.MindFusion.Charting.Collections;
    var Drawing = m.MindFusion.Charting.Drawing;

    //create the chart
    var funnelChartEl = document.getElementById('funnelChart');
    var funnelChart = new Controls.FunnelChart(funnelChartEl);

     //chart customization

The chart object is created with the help of the FunnelChart canvas element, which we get from the html page using the id.

III. Data

Data for the funnel chart is a single list with values. That is why we use the SimpleSeries class. It takes two arguments – one list with the data and one with the labels. We initialize the two arrays:

//initialize data and labels
var data = new Collections.List([100, 90, 80, 37, 17, 7]);
var labels = new Collections.List(["Elementary school", "Middle School", "High school", "Bachelor", "Master", "Doc"]);

Then we create the series and assign it to the series property of the funnelChart object.

//assign a series
funnelChart.series = new Charting.SimpleSeries(data, labels); 

IV. Appearance Customization

We don’t need a legend for the chart that is why we set:

funnelChart.showLegend = false;

A chart needs a title and we set one:

funnelChart.title = "Education Enrollment";

MindFusion JavaScript chart library has a flexible styling model, which allows us to customize the pens and brushes of a chart either directly through the theme property or through styles. A combination of both is possible and that’s what we’ll use. First, we will use the PerElementSeriesStyle for coloring the chart element. This style uses each of the Brush-es that were added to it to paint just one element from the chart. If necessary, the control cycles through the provided Brush -es.

var brushes = new Collections.List([	
	new Drawing.Brush("#193e4e"),
        new Drawing.Brush("#5a7444"),
        new Drawing.Brush("#8eb848"),
        new Drawing.Brush("#678b99"),
        new Drawing.Brush("#a1d0d8"),
        new Drawing.Brush("#c5b28a"),
	var seriesBrushes = new Collections.List();

The PerElementSeriesStyle expects a nested list with Brushes – because a chart can have many series with many elements into it. The same is true for the strokes, but we will add just one Brush, because we want all elements to have one common outlinig:

var strokes = new Collections.List([
	new Drawing.Brush("#f2ebcf"),
var seriesStrokes = new Collections.List();

We repeat the process for StrokeThickness-es and then we create the style object:

funnelChart.plot.seriesStyle = new Charting.PerElementSeriesStyle(seriesBrushes, seriesStrokes, serieStrokeThicknesses);

The theme property exposes many fields that help us customize our chart. We adjust the font and change the highlight stroke, which renders when a chart element is selected:

funnelChart.theme.titleFontSize = 18;
funnelChart.theme.titleFontName = "Roboto";
funnelChart.theme.titleFontStyle = Drawing.FontStyle.Bold;
funnelChart.theme.dataLabelsFontName = "Roboto";
funnelChart.theme.dataLabelsFontSize = 14;
funnelChart.theme.highlightStroke = new Drawing.Brush("#ffcc33");

V. Tooltips

We want our chart to render tooltips. The SimpleSeries does not include tooltips by default and we must do some code twisting to make it show them. First, we create a field tooltips, that is assigned to a list with the desired tooltips:

var tooltips = new Collections.List(["32.7%", "29.5%", "26.2%", "12%", "5%", "2%"]);
funnelChart.series.tooltips = tooltips; 

Then we have to override the supportedLabels property of the Series class to make it return LabelKinds.ToolTip in addition to LabelKinds.InnerLabel.

Object.defineProperty(m.MindFusion.Charting.SimpleSeries.prototype, "supportedLabels", {
            get: function () { return m.MindFusion.Charting.LabelKinds.InnerLabel | m.MindFusion.Charting.LabelKinds.ToolTip; },
            enumerable: true,
            configurable: true

Finally, we must return the appropriate tooltip and the appropriate label, when asked. This is done by overriding the getLabel method of the SimpleSeries class.

m.MindFusion.Charting.SimpleSeries.prototype.getLabel = function (index, kind) {
	if ((kind &amp; m.MindFusion.Charting.LabelKinds.ToolTip) != 0 &amp;&amp; this.tooltips)
		return this.tooltips.items()[index];
	if (this.labels == null)
		return null;
	return this.labels.items()[index];

With that the work on our funnel chart is done and we can enjoy the result:

A Funnel chart in JavaScript

A Funnel chart in JavaScript

Complete source code including the libraries is available for direct download from the link below:

Download the Funnel Chart Sample

About MindFusion JavaScript Chart Library: MindFusion JS Chart is an interactive library for charts and gauges written purely in JavaScript. It supports all common chart types, multiple series, custom data,financial charts, funnel charts, a large selection of gauges and rich styling capabilities. The elegant architecture of the library allows you to create dashboards, charts with multiple different types of series in a single plot, unlimited number of axes, reusable styling themes, various oval and linear gauges. The innovative approach to data lets you define your own data classes by implementing a single interface.
The library also boasts a rich event set, zoom, pan, dragging of the legend and a set of many popular gauges. It is designed and implemented to provide JS developers with the perfect tool to create beautiful, interactive dashboards fast and easy. Download trial directly at http://mindfusion.eu/JavaScript.Chart.zip Get your license today at http://www.javascript-chart-buy.html

A Class Diagram Tool in Java with the Flowchart Library – II

This is the second part of MindFusion step-by-step tutorial on how to create a Java application that reads the contents of a *.jar file and renders class diagram of its API. In the previous blog post we looked at the UI elements that build the application – the UI, the legend panel, the diagram elements. Now we continue with reading the class data and building the class diagram.

I. Reading the Data

The data that we need – the name of the API member, its fields, its type – enum, class, interface as well inherited classes – is stored in a helper class that we’ve created for the purpose and that is called MemberInfo.java. It is a simple class that does nothing else than storing data:

 public MemberInfo( String name, String fullName )
        this.name = name;
        this.fullName = fullName;

        //lists for the methods, fields and constructors.
        methods = new ArrayList();
        fields = new ArrayList();
        constructors = new ArrayList();
        inheritsFrom = "";
        packageName = "";
        isInterface = false;
        isEnum = false;

There is a list with the methods, fields and constructors, as well properties for the name of the package, the class this class inherits from as well boolean values that indicate if this is an enum or interface.

For reading the data we use only classes and methods from the official Java packages – no third party tools or libraries:

            //try to open the jar
            JarFile jarFile = new JarFile(pathToJar);

            //explore the elements found in the *.jar.
            Enumeration e = jarFile.entries();

            URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
            URLClassLoader cl = URLClassLoader.newInstance(urls);
            //if a class is found - read its data
            while (e.hasMoreElements())
                JarEntry je = e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith (".class")) {
                // -6 because of .class file extension.
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');

In a cycle we read all classes in the jar, parse the data we are interested in and filter data that is no relevant to us – private methods, abstract classes etc. The data we acquire for each class is stored in a new MemberInfo object that we add to a collection.

II. Diagram Elements

The diagram elements that we use to render each class are TableNode-s. We use the caption field to show the name of the class. In addition, we use the capabilities of the Java diagram library to render formatted text and add to the caption the name of the package – drawn on a new line.

            //create the TableNode
            TableNode _table = diagram.getFactory().createTableNode(10, 10, 5, 5, 2, info.memberCount());
            //set the name of the member and the package as table caption.
            String caption = "<b>" + info.getName() + "</b>";
            if(info.getPackageName().length() &gt; 0)
                caption += "\n" + info.getPackageName();
            //center the caption
            _table.setCaptionFormat((new TextFormat(Align.Center, Align.Center)));
            //increase the default caption height

It is important to note here that we add an identifier for each table – this will help us find the right TableNode when we later create connections:


By default TableNode-s are drawn with blue. We check if the current object is enum or interface and change the color scheme accordingly:

            //add enums to the list and paint them green
            if(info.isEnum()) {
                _table.setBrush(new SolidBrush(new Color((int) 210, (int) 250, (int) 208)));
            }//add interfaces to the list and paint them yellow
            else if(info.isInterface()) {
                _table.setBrush(new SolidBrush(new Color((int) 250, (int) 235, (int) 140)));
            else //the class nodes are blue
                _table.setBrush(new SolidBrush(new Color((int)197, (int)223, (int)238)));

Then we add table rows for the constructors, methods and fields. Each row has a cell for the image and for the definition of the member:

            //fill the first cells with data for the constructors.
            for (String constructor : info.getConstructors())
                _table.getCell(0, index).setImage(constructorImage);
                _table.getCell(1, index).setText(constructor);

Finally, we look at all MemberInfo objects and draw DiagramLink between each class and the class it derives from, if any:

  for (MemberInfo info : membersList)
                DiagramNode node = diagram.findNodeById (info.getFullName());
                DiagramNode parent = diagram.findNodeById( info.getParent());

                //add inheritance link
                if(node != null &amp;&amp; parent != null)
                    DiagramLink link = diagram.getFactory ().createDiagramLink(node, parent);


III. Containers

Interfaces and enums are drawn in groups at the end of the TableNode-s for classes. This is done using ContainerNode-s. First, we calculate the dimensions of the ContainerNode by measuring all TableNode-s that must fit into it:

            //calculate the location of the node
            int side = (int)Math.ceil(Math.sqrt(tables.size()));
            int rows = (int)Math.ceil((double)tables.size() / side);
            double singleWidth = tables.get(0).getBounds().getWidth();
            double width = 5 * (side + 1) * coef + singleWidth * side;
            double height = (5 * (rows + 1) + 5) * coef;

            double[] rowHeights = new double[rows];
            for (int i = 0; i &lt; tables.size(); i++)
                rowHeights[i / side] = Math.max(tables.get(i).getBounds().getHeight(), rowHeights[i / side]);

            for (double h : rowHeights)
                height += h;

            //initialize the container
            ContainerNode b = diagram.getFactory().createContainerNode (0, 0, width, height);

Here the variable tables is a list with the TableNode-s that must fit into the container. After the ContainerNode is created, the tables must be added and positioned in it:

            int index = 0;
            for (TableNode e : tables)

                double x = (index % side) * (5 + singleWidth);
                double y = 0;

                for (int r = 0; r &lt; index / side; r++)
                    y += 5 * coef + rowHeights[r];

                //adjust the size of the node
                e.setBounds(new Rectangle2D.Double(x + 5 * coef, y + 10 * coef,                   e.getBounds().getWidth(), e.getBounds ().getHeight()));


Finally we adjust the appearance of the ContainerNode to make it look better and in line with the TableNode-s:

            //customize the container
            b.setCaptionFormat((new TextFormat(Align.Center,  Align.Center)));
            b.setHandlesStyle( HandlesStyle.HatchHandles3 );
            b.setFont(new Font("Verdana", Font.BOLD, 4));
            //no shadow

It’s important to note that the bounds of the container must be updated for the changes to take effect:

            //update the container size.

IV. Diagram Layout

The last part of the application deals with diagram layout. This is very important because in the common scenario we expect to read *.jar files with tens of classes and proper visual arrangement of the flowchart is the key to its usability.

We decide to use the TreeLayout, which is meant exactly to arrange diagrams with nodes on several levels as we expect the class hierarchies to be. It is easy to apply the layout – we create an instance of it and after setting some initial customization we call its arrange method:

         TreeLayout layout = new TreeLayout();

        //the layout type is Centered
        //allow reversed links
        //the type of links will be cascading
        //specify the distance between levels of tree nodes
        //groups must be preserved.


It is easy to understand the type of the settings we’ve used – thanks to the self-explanatory names of the layout class you can see that we specify that the TreeLayout will be centered, the links will be reversed, then we change the link style and the distance between levels. Finally, we specify that the layout of groups must be preserved.

The interesting part is at the end. We must find the ContainerNode-s with the enums and interfaces and move them to the end of the diagram. Here is how:

        // Place enums and delegates at the end
        DiagramNode enums = diagram.findNode(":enums");
        DiagramNode delegates = diagram.findNode(":interfaces");

        double x = 0;
        //calculate the location of each node to find out the last one
        for (DiagramNode node : diagram.getNodes())
        	if (node instanceof TableNode)
        		x = Math.max(x, node.getBounds().getX() +  node.getBounds().getWidth());

        //move enums to the right of the last class node.
        if (enums != null)
            enums.moveTo((float)x + 5f, (float)5);
            x = enums.getBounds().getX() + enums.getBounds().getWidth ();

        if (delegates != null)
            delegates.moveTo((float)x + 5, 5);

We cycle through each TableNode and always move the containers to the end of the rightmost TableNode that we find. Let’s not forget to resize the diagram after we are done:


With this our application is ready and we test it with an arbitrary *.jar file. Here is the result:

Class Diagram Application in Java

Class Diagram Application in Java

You can download the complete source code of the sample from here:

Download the Class Diagram Tool in Java Application

MindFusion support team welcomes your questions about the Java diagram library or any other of our programming tools at the discussion board or per e-mail at support@mindfusion.eu

About Diagramming for Java Swing: MindFusion.Diagramming for Java Swing provides your Java application with all necessary functionality to create and customize a diagram. The library is very easy to integrate and program. There are numerous utility methods, rich event set, more than 100 predefined shapes. The tool supports a variety of ways to render or export the diagram, advanced node types like TreeView nodes, hierarchical nodes, tables, container nodes and many more. There are 15 automatic layouts, various input / output options and fully customizable appearance. A detailed list with JDiagram’s features is uploaded here. You can check the online demo to see some of the functionality implemented.

Diagramming for Java Swing is royalty free, there are no distribution fees. Licenses depend on the count of developers using the tool – check here the prices.

Collaborative drawing with MindFusion.Diagramming and SignalR

In this post we’ll show how to use the ASP.NET MVC diagram library and SignalR to implement collaborative drawing of diagrams. This can be useful in visual planning tools where users work together on a task, such as project management or mind-mapping applications.

The complete sample project is available here –

Start by creating an ASP.NET MVC application in Visual Studio. Open Tools -> Library Package Manager -> Package Manager Console and install the MindFusion.Diagramming.Mvc package –

Install-Package MindFusion.Diagramming.Mvc 

While we are there, also install the SignalR package –

install-package Microsoft.AspNet.SignalR

From the project’s context menu, Add submenu, select OWIN startup class and add SignalR to the OWIN pipeline by calling –


Now lets add a diagram view to the home page at Views/Home/Index.cshtml, load the necessary script files and wire up diagram event handlers that will send change notifications to the hub –

@using MindFusion.Diagramming
@using MindFusion.Diagramming.Mvc

    var diagView = new DiagramView("diagramView")

    diagView.Diagram.DefaultShape = Shapes.Ellipse;

@Html.DiagramView(diagView, new { style = "width:700px; height:600px;" })

@section scripts

The hub will synchronize operations done on the diagram by one client by sending a notification to all other connected clients. From the project context menu add a SignalR hub class, naming it DiagramHub. The model class we’ll use to describe node changes looks like this –

public class NodeModel
    public double X { get; set; }

    public double Y { get; set; }

    public double Width { get; set; }

    public double Height { get; set; }

    public string Id { get; set; }

    public string Text { get; set; }

Add these three methods to the hub class to synchronize node creation, move, resize and edit-text operations –

public void NodeCreated(NodeModel clientModel)
public void NodeModified(NodeModel clientModel)
public void NodeTextEdited(NodeModel clientModel)

The diagram event handlers in MindMap.js fill in the model objects and call respective hub methods –

function onNodeCreated(s, e)
    var hubId = $.connection.hub.id;
    e.node.id = hubId + s.getItems().length;

    var r = e.node.bounds;
    var model =
        id: e.node.id,
        x: r.x,
        y: r.y,
        width: r.width,
        height: r.height

function onNodeModified(s, e)
    var r = e.node.bounds;
    var model =
        id: e.node.id,
        x: r.x,
        y: r.y,
        width: r.width,
        height: r.height

function onNodeTextEdited(s, e)
    var model =
        id: e.node.id,
        text: e.getNewText()

Handle notifications sent from server to clients by updating the diagram from received model objects –

$(function ()
    diagramHub = $.connection.diagramHub;
    diagramHub.client.nodeCreated = function (model)
        var node = diagram.factory.createShapeNode(
            model.x, model.y, model.width, model.height);
        node.id = model.id;
    diagramHub.client.nodeModified = function (model)
        var node = findNode(model.id);
            new MindFusion.Drawing.Rect(
                model.x, model.y, model.width, model.height),
    diagramHub.client.nodeTextEdited = function (model)
        var node = findNode(model.id);

Finally add these helper functions for finding items and storing a global diagram reference –

function onDiagramLoaded(s, e)
    diagram = s;

function findNode(id)
    for (var i = 0; i < diagram.nodes.length; i++)
        var node = diagram.nodes[i];
        if (id == node.id)
            return node;
    return null;

function findLink(id)
    for (var i = 0; i < diagram.links.length; i++)
        var link = diagram.links[i];
        if (id == link.id)
            return link;
    return null;

Start several copies of the application in separate browser instances on your system (or even on different machines if you publish it on IIS or Azure). Now start drawing nodes, moving them or editing their text – changes done on the diagram in one browser will be immediately reflected in all other browsers connected to the hub. However we aren’t yet synchronizing link operations; lets fix that –

public class LinkModel
    public string Id { get; set; }

    public string OriginId { get; set; }

    public string DestinationId { get; set; }

    public string Text { get; set; }

Add following hub methods in server class –

public void LinkCreated(LinkModel clientModel)
public void LinkModified(LinkModel clientModel)
public void LinkTextEdited(LinkModel clientModel)

Call them from respective JavaScript handlers of diagram link events –

function onLinkCreated(s, e)
    var hubId = $.connection.hub.id;
    e.link.id = hubId + s.getItems().length;

    var model =
        id: e.link.id,
        originId: e.link.getOrigin().id,
        destinationId: e.link.getDestination().id,

function onLinkModified(s, e)
    var hubId = $.connection.hub.id;
    var model =
        id: e.link.id,
        originId: e.link.getOrigin().id,
        destinationId: e.link.getDestination().id,

function onLinkTextEdited(s, e)
    var model =
        id: e.link.id,
        text: e.getNewText()

Handle link-related client notifications by creating or modifying links –

diagramHub.client.linkCreated = function (model)
    var link = diagram.factory.createDiagramLink(
        findNode(model.originId), findNode(model.destinationId));
    link.id = model.id;
diagramHub.client.linkModified = function (model)
    var link = findLink(model.id);
diagramHub.client.linkTextEdited = function (model)
    var link = findLink(model.id);

Now the application will also synchronize link operations across all connected clients. Here’s a small diagram synchronized between three different browsers –
collaborative mind map

The sample above uses MindFusion’s ASP.NET MVC API. Code for other frameworks will look similar as MindFusion maintains same diagramming model for multiple platforms. You can download the trial version of any MindFusion.Diagramming component from this page.


A Class Diagram Tool in Java with the Flowchart Library – I

This blog post is a step-by-step guide on how to create a tool that parses *.jar files and builds the class hierarchy. The visualization of the diagram is performed by MindFusion Java Swing Diagram library.

Here is an image of the final application:

Class Library Tool in Java

Class Library Tool in Java

In part one we will take a look at the controls that build the user interface for the application.

I. UI Controls

We will use three controls from the diagram library:

    private Diagram diagram;
    private DiagramView diagramView;
    private ZoomControl zoomer;

One JScrollPane:

private JScrollPane _scrollPane;

and a JPanel for the legend and a JMenuBar.

    JPanel controlsPanel = new JPanel();
    JMenuBar menuBar;

Those controls build the user interface. At the top is the menu bar with menus for handling the *.jar files. In the center is a scrollable area that contains the diagram. Right to it is a zoom control. At the bottom is the panel with the legend – images and text that explain the colors and symbols on the class diagram.

II. The Diagram Controls

The three diagram controls are the Diagram, the DiagramView and the ZoomControl. The diagram needs a diagramView to render itself onto. The diagramView users a scrollPane to provide scroll functionality for the flowchart. The zoomControl is a typical Java Swing control, we set a few customization options on it to make it pass the layout of our application.

       //diagram initialization
        diagram = new Diagram();

We set auto resize for the diagram and assign it to the diagramView:

        //initialize a diagramView that will render the diagram.
        diagramView = new DiagramView(diagram);

The scrollPane is initialized with the diagramView and scrolls automatically when the view is bigger than the available size:

         //use a scroll pane to host large diagrams
        _scrollPane = new JScrollPane(diagramView);

The zoomControl is also attached to the diagramView. It’s important that we set its Dimension, the width will be used by the Java layout manager to calculate the available space for it on the application.

        //provide a zoomer for the diagram
        zoomer = new ZoomControl();
        zoomer.setPreferredSize(new Dimension(70, 50));

The arrangement of the controls in the JFrame is done with the BorderLayout. It’s important that we set the layout before we start adding the controls:

     getContentPane().setLayout(new BorderLayout());
     this.add(zoomer, BorderLayout.EAST);
     this.add(createLegendPanel(), BorderLayout.SOUTH);

The zoomer is to the right, the legend panel is at the bottom. The last control that we add is the scrollPane with the diagram, we align it to the center, which means that all the available space would be allocated to her.

     this.add(_scrollPane, BorderLayout.CENTER);

Finally, we create the menu bar.


III. The Legend Panel

The legend panel is a JPanel with BoxLayout of type “LINE_AXIS”.

        JPanel controlsPanel = new JPanel();
        controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.LINE_AXIS));
        controlsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

The legend items are ImageIcon-s – for each symbol in the diagram there’s an icon. We have also created images for the colors of the diagram. Each icon is rendered with explanation label.

Generally, each item on the LegendPanel is initialized like this:

        //create labels for each item on the legend
        JLabel label = new JLabel("Constructor", constructorIcon, JLabel.CENTER);
        controlsPanel.add(Box.createRigidArea(new Dimension(10, 0)));

The layout distributes evenly the available space between the items and we get an easy-to-read legend at the bottom of the application.

IV. The Menu

The menu at the top is implemented as a JMenuBar, which uses mnemonic keys and accelerators to grant access to the menu items with keyboard shortcuts. The only menu item and submenu items currently present are File -> Open jar.

        //Build the first menu.
        menu = new JMenu("File");
                "File operations");

The “Open jar” command uses action listener, which brings up the Open File diagolg. This is a JFileChooser, which filters all files except *.jar files.

     //the method that handles events
    public void actionPerformed(ActionEvent e)
        //identify the command
        if ("open_jar".equals(e.getActionCommand())) {

            //a list with MemberInfo objects that hold class info
            ArrayList membersList = new ArrayList();
            fileChooser = new JFileChooser();

            //set the default directory to this file's directory

            //filter only *.jar files
            FileFilter filter = new FileNameExtensionFilter(null, "jar");

If the method confirms that the user has selected a valid jar, the path to the file is provided to the method that reads and parses the jar, which will be topic for the second part of this tutorial.

The whole sample is available for direct download from this link:

Download the Class Diagram Tool in Java Application

MindFusion support team welcomes your questions about the Java diagram library or any other of our programming tools at the discussion board or per e-mail at support@mindfusion.eu

About Diagramming for Java Swing: MindFusion.Diagramming for Java Swing provides your Java application with all necessary functionality to create and customize a diagram. The library is very easy to integrate and program. There are numerous utility methods, rich event set, more than 100 predefined shapes. The tool supports a variety of ways to render or export the diagram, advanced node types like TreeView nodes, hierarchical nodes, tables, container nodes and many more. There are 15 automatic layouts, various input / output options and fully customizable appearance. A detailed list with JDiagram’s features is uploaded here. You can check the online demo to see some of the functionality implemented.

Diagramming for Java Swing is royalty free, there are no distribution fees. Licenses depend on the count of developers using the tool – check here the prices.