Some ideas are easiest to explain as boxes and the lines between them: the services of a system and who calls whom, an organization chart, a dependency map, or a pipeline the user builds by wiring blocks together. NodeGraph covers both kinds. It shows a diagram the application lays out, and it’s an editor in which the user drags nodes and connects their ports.

The component is in com.codename1.ui.graph. It draws from a model in com.codename1.graph that has no user interface in it, so a graph can be built, laid out, tested and stored without a form on the screen. The arrangements are in com.codename1.graph.arrange.

NodeGraph paints its nodes and edges directly instead of building a component for each one. A graph with thousands of nodes pans and zooms the way one with ten does, because only what’s on the screen is drawn. When the user zooms far out, nodes are drawn as plain cards without text.

A first graph

A GraphNode has an id and a label, and addEdge connects two nodes by their ids. An arrangement gives each node a position, and fitToView zooms so the whole graph is in view.

DefaultGraphModel model = new DefaultGraphModel();
model.addNode(new GraphNode("web", "Web app"));
model.addNode(new GraphNode("api", "API gateway"));
model.addNode(new GraphNode("orders", "Orders"));
model.addNode(new GraphNode("billing", "Billing"));
model.addNode(new GraphNode("db", "Database"));
model.addEdge("web", "api");
model.addEdge("api", "orders");
model.addEdge("api", "billing");
model.addEdge("orders", "db");
model.addEdge("billing", "db");

NodeGraph graph = new NodeGraph(model);
graph.arrange(new LayeredArrangement(), false);

Form form = new Form("Services", new BorderLayout());
form.add(BorderLayout.CENTER, graph);
form.show();
graph.fitToView();

Give the graph the center of a BorderLayout. It pans and zooms inside the room it’s given, so it doesn’t belong in a container that scrolls too. The user pans by dragging the background, zooms with a pinch or the mouse wheel, and taps a node to select it.

Ten services in layers, from the two clients through an API gateway to the services and the stores behind them
Figure 297. A system map with the layered arrangement
The service map drawn light on dark
Figure 298. The same map in the dark appearance and on iOS
The service map in the iOS theme

Groups, labels and styles

A GraphGroup draws a frame around the nodes that name it, with its label in the corner. Tapping that label collapses the group to a single card, and tapping it again opens it. An edge can carry a label, drawn in a pill at its middle, and a style key that the renderers use to pick a color.

DefaultGraphModel model = new DefaultGraphModel();
model.addNode(new GraphNode("orders", "Orders"));
model.addNode(new GraphNode("billing", "Billing"));
model.addNode(new GraphNode("db", "Database"));

model.addGroup(new GraphGroup("backend", "Backend"));
model.getNode("orders").setGroupId("backend");
model.getNode("billing").setGroupId("backend");

GraphEdge write = model.addEdge("orders", "db");
write.setLabel("writes");
model.getNode("db").setStyleKey("storage");

setEdgeStyle chooses how edges are drawn: EDGE_STRAIGHT, EDGE_ORTHOGONAL, EDGE_CURVED, or EDGE_AUTO, which follows the route an arrangement computed when there is one.

The clients and the backend services each framed in a titled group, with edges drawn in right angles and labeled SQL
Figure 299. Two groups, edge labels and orthogonal edges

Arrangements

An arrangement reads the model and returns a position for every node. arrange(arrangement, true) animates the nodes to their new places, and false moves them at once. A graph with no arrangement keeps the positions its nodes were given, which is the manual mode a node editor uses.

DefaultGraphModel model = new DefaultGraphModel();
model.addNode(new GraphNode("ceo", "CEO"));
model.addNode(new GraphNode("cto", "CTO"));
model.addNode(new GraphNode("cfo", "CFO"));
model.addEdge("ceo", "cto");
model.addEdge("ceo", "cfo");
NodeGraph graph = new NodeGraph(model);

LayeredArrangement layered = new LayeredArrangement();
layered.setDirection(LayeredArrangement.LEFT_TO_RIGHT);
graph.arrange(layered, true);

TreeArrangement tree = new TreeArrangement();
tree.setRootId("ceo");
graph.arrange(tree, true);

graph.arrange(new RadialArrangement(), true);

ForceArrangement force = new ForceArrangement();
force.setIdealLength(140);
graph.arrange(force, true);
ArrangementGood for

LayeredArrangement

Flows and dependencies. Nodes go in layers along the direction of their edges, ordered to keep edges from crossing, and long edges are routed around the layers between their ends.

TreeArrangement

Hierarchies such as an organization chart. Each parent sits centered over its children, and subtrees never overlap.

RadialArrangement

The same hierarchy as rings around the root.

ForceArrangement

Networks with no natural direction. Connected nodes pull together and all nodes push apart, until the graph settles.

A chief executive above three officers, each above their departments
Figure 300. An organization chart with the tree arrangement
The chief executive in the center with the officers on the first ring and their departments on the second
Figure 301. The same chart with the radial arrangement
Three hubs, each surrounded by the hosts connected to it
Figure 302. A network with the force arrangement

ForceArrangement can also run live while the user works. Dragged nodes stay where the user holds them, and the rest of the graph moves around them.

NodeGraph graph = new NodeGraph();
graph.setLiveArrangement(new ForceArrangement());

A node marked with setPinned(true) stays where it’s while ForceArrangement arranges the others.

A node editor

Give a node ports and the graph becomes an editor. Inputs are drawn on one side of the card and outputs on the other. With editing on, the user drags from an output to an input to connect them, drags nodes around, long presses or Shift-drags the background to select several with a box, and deletes what’s selected with deleteSelection. setLabelEditing(true) also lets the user double tap a node to rename it.

DefaultGraphModel model = new DefaultGraphModel();
model.addNode(new GraphNode("noise", "Noise", 0, 0, 160, 90)
        .addOutput("out", "Value", "float"));
model.addNode(new GraphNode("color", "Color ramp", 240, 0, 160, 90)
        .addInput("in", "Factor", "float")
        .addOutput("out", "Color", "color"));
model.addNode(new GraphNode("material", "Material", 480, 0, 160, 110)
        .addInput("base", "Base color", "color")
        .addInput("rough", "Roughness", "float"));

NodeGraph graph = new NodeGraph(model);
graph.setEditingEnabled(true);
graph.setGridVisible(true);
graph.setSnap(20);
graph.setEdgeStyle(NodeGraph.EDGE_CURVED);
Four nodes with inputs on the left and outputs on the right, wired from a noise source through a color ramp into a material
Figure 303. A node editor: typed ports connected by curved edges, on a grid

A port has a type. The model’s ConnectionValidator refuses an edge between ports whose types differ, from an input to an input, from a node to itself, a second copy of an edge that exists, and an edge past a port’s setMaxConnections limit. setAllowCycles(false) also refuses an edge that would close a loop. While the user drags a connection, the port under the finger shows whether it would accept it, and a drop on a port that refuses it connects to the nearest one on that node that accepts it.

Nodes without ports can be connected too. A selected node shows a handle on its trailing edge, and dragging from it, or from a long press on the node, draws a new edge to wherever it’s dropped.

Listening and refusing

Every change the user makes is offered to the graph’s listeners before it reaches the model. A listener that returns false refuses it, and nothing changes. Extend GraphAdapter to implement only what you need.

NodeGraph editor = new NodeGraph();
editor.addGraphListener(new GraphAdapter() {
    @Override
    public boolean edgeCreating(NodeGraph g, GraphNode source, GraphPort sourcePort,
            GraphNode target, GraphPort targetPort) {
        return !"material".equals(source.getId());
    }

    @Override
    public void edgeCreated(NodeGraph g, GraphEdge edge) {
        Log.p("Connected " + edge.getSourceId() + " to " + edge.getTargetId());
    }
});

A model of your own implements GraphModel, or extends AbstractGraphModel for the listener plumbing. Its moveNode, connect, removeNode and the other edit methods return false to refuse a change, which makes a read-only model the default.

Components inside nodes

Nodes are painted, but a node can carry a real component as well: a slider, a text field or a button. The factory is asked for one per node, and a node it returns null for stays painted. The component is placed over the node’s card while the node is on the screen and the zoom is above setComponentZoom. Below that, the card is painted alone.

NodeGraph graph = new NodeGraph();
graph.setNodeComponentFactory(new NodeComponentFactory() {
    @Override
    public Component createComponent(NodeGraph g, GraphNode node) {
        if (!"material".equals(node.getId())) {
            return null;
        }
        return new Slider();
    }
});
The node editor with a real slider inside the roughness node
Figure 304. A slider inside a node

Flow charts and swim lanes

A node has a shape as well as a size. setShape takes one of the names in GraphShapes: a terminator, a decision diamond, a document, a database cylinder and the other symbols of a flow chart. The shape is used three times, and the three agree. It’s the outline that’s painted, the area a tap has to land in, and the line an edge stops at.

An edge has a line style, solid, dashed or dotted, and an arrow kind for each of its ends. A lane is a group with bounds of its own, made with GraphGroup.lane. It’s drawn as a band with a title along one side, and a node dragged from one lane into another joins it.

DefaultGraphModel model = new DefaultGraphModel();
model.addGroup(GraphGroup.lane("shop", "Shop", true, 0, 0, 620, 150));
model.addGroup(GraphGroup.lane("warehouse", "Warehouse", true, 0, 150, 620, 150));

GraphNode start = new GraphNode("start", "Order placed", 50, 48, 110, 54)
        .setShape(GraphShapes.TERMINATOR);
start.setGroupId("shop");
model.addNode(start);
GraphNode paid = new GraphNode("paid", "Paid?", 220, 40, 110, 70)
        .setShape(GraphShapes.DECISION);
paid.setGroupId("shop");
model.addNode(paid);
GraphNode cancel = new GraphNode("cancel", "Cancelled", 400, 48, 110, 54)
        .setShape(GraphShapes.TERMINATOR);
cancel.setGroupId("shop");
model.addNode(cancel);
GraphNode stock = new GraphNode("stock", "Stock", 50, 198, 110, 54)
        .setShape(GraphShapes.DATABASE);
stock.setGroupId("warehouse");
model.addNode(stock);
GraphNode pick = new GraphNode("pick", "Pick items", 220, 198, 110, 54)
        .setShape(GraphShapes.SUBPROCESS);
pick.setGroupId("warehouse");
model.addNode(pick);
GraphNode ship = new GraphNode("ship", "Ship", 400, 198, 110, 54)
        .setShape(GraphShapes.DATA);
ship.setGroupId("warehouse");
model.addNode(ship);

model.addEdge("start", "paid");
model.addEdge("paid", "cancel").setLabel("no");
model.addEdge("paid", "pick").setLabel("yes");
model.addEdge("pick", "ship");
GraphEdge reads = model.addEdge("stock", "pick");
reads.setLineStyle(GraphEdge.LINE_DASHED);
reads.setTargetArrow(GraphEdge.ARROW_OPEN);

NodeGraph graph = new NodeGraph(model);
graph.setEdgeStyle(NodeGraph.EDGE_ORTHOGONAL);
graph.setEditingEnabled(true);
graph.setResizable(true);
Six flow chart symbols in two bands titled Shop and Warehouse: a rounded start, a decision diamond with yes and no branches, a database cylinder joined to a step by a dashed line
Figure 305. A flow chart in two swim lanes

LayeredArrangement.setRespectLanes(true) arranges a chart without taking a node out of its lane. The layers run along the lanes, and each node stays in the band of its own. Nodes in no lane go past the last one.

With setResizable(true) a selected node shows a handle on each corner, and dragging one resizes it. The edges of a lane are dragged the same way. To draw an outline that isn’t in the list, implement GraphShape and give it a name with GraphShapeRegistry.register.

A palette of nodes

GraphPalette is a strip of node templates beside a graph. The user drags a template onto the canvas, or taps it and then taps where the node should go. A GraphNodeTemplate holds what the new node starts with: its label, shape, size and ports. The same palette serves a flow chart, where the templates are shapes, and a node editor, where they’re the kinds of node with their ports.

NodeGraph graph = new NodeGraph();
GraphPalette palette = new GraphPalette(graph);
palette.add(new GraphNodeTemplate("Step").setShape(GraphShapes.RECT));
palette.add(new GraphNodeTemplate("Decision")
        .setShape(GraphShapes.DECISION).setSize(110, 70));
palette.add(new GraphNodeTemplate("Stored data").setShape(GraphShapes.DATABASE));
palette.add(new GraphNodeTemplate("Multiply")
        .addInput("a", "A", "number")
        .addInput("b", "B", "number")
        .addOutput("out", "Result", "number"));

Container editor = new Container(new BorderLayout());
editor.add(BorderLayout.WEST, palette);
editor.add(BorderLayout.CENTER, graph);

A listener hears nodeCreating before the node reaches the model and may change it or refuse it.

Values on input ports

An input that nothing is connected to often needs a value of its own: the factor of a multiplication, the color of a material. GraphPort.setValue holds it, and a PortEditorFactory supplies the small component the user changes it with. The editor is shown beside the port while nothing is connected to it.

NodeGraph graph = new NodeGraph();
graph.setPortEditorFactory(new PortEditorFactory() {
    @Override
    public Component createEditor(final NodeGraph g, GraphNode node, final GraphPort port) {
        if (!"number".equals(port.getType())) {
            return null;
        }
        final TextField field = new TextField(String.valueOf(port.getValue()), "", 4, TextField.DECIMAL);
        field.addActionListener(e -> g.setPortValue(port, Double.valueOf(field.getAsDouble(0))));
        return field;
    }
});

DefaultGraphEdgeRenderer.setColorByPortType(true) draws each edge in the color of the type it carries, so a number, a color and a texture can be told apart at a glance.

Saving, undo and the clipboard

GraphJson writes a whole model as JSON text and reads it back, lanes and port values included. A node’s user data is written through a UserDataCodec when you supply one.

NodeGraph graph = new NodeGraph();
Preferences.set("diagram", GraphJson.toJson(graph.getModel()));

String saved = Preferences.get("diagram", null);
if (saved != null) {
    try {
        graph.setModel(GraphJson.fromJson(saved));
    } catch (IOException notAGraph) {
        Log.e(notAGraph);
    }
}

Every edit the user makes can be undone: a move, a connection, a deletion, a resize or a paste. One gesture is one step, so deleting five selected nodes and their edges is undone together. Changes the application makes to the model directly aren’t recorded.

The steps go into the application’s history, UndoHistory.getGlobal(), which the Kanban board and the rich text and code editors share. A single Undo button takes back the last change wherever it was made, and brings the component it was made in back into view. setUndoHistory gives the graph a history of its own, or turns undo off with null. Showing another model drops that model’s steps and keeps the rest.

final NodeGraph graph = new NodeGraph();
// every edit goes into the application's history; one button serves
// the graph and any other component that records into it
UndoHistory history = UndoHistory.getGlobal();
Button undo = new Button("Undo");
undo.addActionListener(e -> graph.undo());
history.addListener(h -> undo.setEnabled(h.canUndo()));
Button redo = new Button("Redo");
redo.addActionListener(e -> graph.redo());
Button copy = new Button("Copy");
copy.addActionListener(e -> graph.copySelection());
Button paste = new Button("Paste");
paste.addActionListener(e -> graph.paste());
Button duplicate = new Button("Duplicate");
duplicate.addActionListener(e -> graph.duplicateSelection());

Copied nodes go to the clipboard as JSON together with the edges between them, and a paste gives them new ids. With a keyboard, Delete removes the selection, and with Control or Command, C, X, V and D copy, cut, paste and duplicate, Z undoes and Shift-Z redoes. A phone has no such keys, so put the same methods behind a menu or a toolbar.

Finding your way

setMinimapVisible(true) shows a small map of the whole graph in a corner, with the part on the screen outlined. Tapping the map moves the view there. centerOn(node) moves the view to a node, setZoomRange limits how far the user can zoom, and toImage paints the whole graph into an image for sharing or printing.

Styling

The graph is styled through these UIIDs, which the native themes define:

UIIDUsed for

NodeGraph

The background

NodeGraphGrid

The grid lines, when the grid is on

NodeGraphNode

A node’s card, its border and its text

NodeGraphNodeSelected

A selected node

NodeGraphGroup

A group’s frame and label

NodeGraphPort

The ports

NodeGraphEdge

The edges and their arrows

NodeGraphEdgeLabel

The pill behind an edge label

NodeGraphMinimap

The minimap

NodeGraphLane

The band of a lane

NodeGraphLaneHeader

The title strip of a lane

NodeGraphHandle

The resize handles of a selected node

NodeGraphPalette

The background of a palette

NodeGraphPaletteItem

The label under a template in a palette

For more than colors, implement GraphNodeRenderer or GraphEdgeRenderer, or extend the default ones, and pass them to setNodeRenderer and setEdgeRenderer.