PrimeFaces - Diagram Example

[Updated: Jul 2, 2017, Created: Jul 2, 2017]

Following example shows how to use PrimeFaces's Diagram component to display SVG content.

JSF page

src/main/webapp/index.xhtml

<h:body style="margin:50px;">
    <h2>PrimeFaces Diagram Example</h2>
    <p:diagram value="#{myBean.model}"
               styleClass="panel"/>

    <style type="text/css">
    .my-box {
        border:1px solid #aaa;
        width:70px;
        height:20px;
        padding:10px;
        background:#eee;
        text-align: center;
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.4);
    }
    .panel{
        margin:0 auto;
        height:230px;
        width:200px;
        background:pink;
    }

    </style>
</h:body>

The manage bean

@ManagedBean
@ViewScoped
public class MyBean {
  private DefaultDiagramModel model;

  @PostConstruct
  public void init() {
      model = new DefaultDiagramModel();
      model.setMaxConnections(-1);

      //Box 1
      Element e1 = new Element();
      e1.setDraggable(false);
      e1.setData("Box 1");
      e1.setStyleClass("my-box");
      e1.setX("50px");
      e1.setY("15px");
      //appending a dot to bottom
      DotEndPoint p1 = new DotEndPoint();
      p1.setAnchor(EndPointAnchor.BOTTOM);
      p1.setRadius(4);
      e1.addEndPoint(p1);
      model.addElement(e1);

      //Box 2
      Element e2 = new Element();
      e2.setDraggable(false);
      e2.setData("Box 2");
      e2.setStyleClass("my-box");
      e2.setX("50px");
      e2.setY("160px");
      //appending a dot to top
      DotEndPoint p2 = new DotEndPoint();
      p2.setAnchor(EndPointAnchor.TOP);
      p2.setRadius(4);
      e2.addEndPoint(p2);
      model.addElement(e2);

      //connecting the two dots
      Connection c = new Connection();
      c.setSource(p1);
      c.setTarget(p2);
      c.setConnector(new StraightConnector());
      model.connect(c);
  }

  public DefaultDiagramModel getModel() {
      return model;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used :

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • datafactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.3.9

Diagram Example Select All Download
  • diagram-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also