JavaFX 2: Simple Graphs

It's pretty easy to create a graphs in the JavaFX application, because there are a lot of neat libraries on the Internet.

Trouble comes when you need to stick with JavaFX 2.

This very very simple library will let you to create simple graphs like this one:

Simple Graphs - preview


Let's consider a simple JavaFX 2 application:

public class HelloWorld extends Application {

    private void init(Stage primaryStage) {
        // TODO
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
} 

We will fill the init method to set up the scene showing the graph nodes from the picture above.

First, we need the parent node:

final BoxNode parent = new BoxNode("Parent", 250, 0);

Then the children nodes:

final BoxNode myNode1 = new BoxNode("MyNode 1", 0, 200);
final BoxNode myNode2 = new BoxNode("MyNode 2", 300, 400);

Second, we connect the nodes with each other (the parent to children, the first child to the second one and also with itself):

parent.addArrowTo(myNode1, "arrow 1");
parent.addArrowTo(myNode2, "arrow 2");
myNode1.addArrowTo(myNode2, "arrow 3");
myNode1.addArrowTo(myNode1, "arrow round");

Finally, we all the nodes to a group (javafx.scene.Group) and the group to the scene:

final Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().addAll(parent, myNode1, myNode2);

That's all!

The library is available as a JAR or source archive.