Skip to content
Steffen edited this page Jun 7, 2022 · 4 revisions

In this tutorial we are creating a simple JavaFX application containing 2 graph nodes that can be dragged around and connected to each other.

Prerequisites

Ensure that

  • Java 17 is installed.
  • The graph editor and its dependencies are on your classpath.

Create the JavaFX application

To begin with, we are creating an empty JavaFX application:

	import javafx.application.Application;
	import javafx.scene.Scene;
	import javafx.stage.Stage;
	import io.github.eckig.grapheditor.GraphEditor;
	import io.github.eckig.grapheditor.core.DefaultGraphEditor;

	public class GraphEditorTutorial extends Application
	{
		public static void main(final String[] args)
		{
			launch(args);
		}

		@Override
		public void start(final Stage primaryStage) throws Exception
		{
			GraphEditor graphEditor = new DefaultGraphEditor();
			Scene scene = new Scene(graphEditor.getView(), 800, 600);
			primaryStage.setScene(scene);
			primaryStage.show();
		}
	}

If you run this you should see an empty stage.

Set a graph model

The visible state of the graph is stored in an EMF model. Create a new model instance and set it in the graph editor:

    GModel model = GraphFactory.eINSTANCE.createGModel();
    graphEditor.setModel(model);

Add nodes and connectors

Now we are creating a node with one input and one output connector:

	private GNode createNode()
	{
		GNode node = GraphFactory.eINSTANCE.createGNode();

		GConnector input = GraphFactory.eINSTANCE.createGConnector();
		GConnector output = GraphFactory.eINSTANCE.createGConnector();

		input.setType("left-input");
		output.setType("right-output");

		node.getConnectors().add(input);
		node.getConnectors().add(output);

		return node;
	}

And now another way to create two additional nodes and add those nodes to the model:

	private void addNodes(GModel model)
	{
		GNode firstNode = createNode();
		GNode secondNode = createNode();

		firstNode.setX(150);
		firstNode.setY(150);

		secondNode.setX(400);
		secondNode.setY(200);
		secondNode.setWidth(200);
		secondNode.setHeight(150);

		Commands.addNode(model, firstNode);
		Commands.addNode(model, secondNode);
	}

Call this method after setting your model in the graph editor, for example:

    GModel model = GraphFactory.eINSTANCE.createGModel();
    graphEditor.setModel(model);
    addNodes(model);

Start the application and you should see the nodes. Try dragging, resizing, and connecting them together.