Lesson: Creating an Empty View

First things first. We begin our viewer application by creating a boring, empty view. Figure 1.1, “An empty yFiles view” illustrates where we want to go.

Figure 1.1. An empty yFiles view

An empty yFiles view

The actual source code that creates this view is really simple, and mainly consists of standard code to set-up a Java Swing application's GUI.

Taking a Closer Look

Let's take a look at the relevant source code of the SimpleGraphViewer1 application.

Example 1.1. SimpleGraphViewer1 source code

public class SimpleGraphViewer1 {
  JFrame frame;
  /** The yFiles view component that displays (and holds) the graph. */
  Graph2DView view;

  public SimpleGraphViewer1(Dimension size, String title) {
    view = createGraph2DView();
    frame = createApplicationFrame(size, title, view);
  }

  private Graph2DView createGraph2DView() {
    Graph2DView view = new Graph2DView();
    return view;
  }

  /** Creates a JFrame that will show the demo graph. */
  private JFrame createApplicationFrame(Dimension size, String title, 
                                        JComponent view) {
    JPanel panel = new JPanel(new BorderLayout());
    panel.setPreferredSize(size);
    // Add the given view to the panel.
    panel.add(view, BorderLayout.CENTER);
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getRootPane().setContentPane(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    return frame;
  }

  public void show() { frame.setVisible(true); }

  public static void main(String[] args) {
    SimpleGraphViewer1 sgv = 
      new SimpleGraphViewer1(new Dimension(400, 200), 
                             SimpleGraphViewer1.class.getName());
    sgv.show();
  }
}

Ultimately, SimpleGraphViewer1 has only one yFiles-specific line of code:

// Create the yFiles view (aka "canvas").
Graph2DView view = new Graph2DView();

This single line in the createGraph2DView method is where the yFiles view component, which is of type Graph2DView, is created. In method createApplicationFrame it is then added to the application's Java Swing GUI.

Important

Graph2DView provides its own scrollbar support, which is why we won't need to add it to a JScrollPane in particular when building our application's GUI.

Note that even though the view seems empty at first, it actually already displays a graph. Read on....

Related Resources

You will find related information in the yFiles for Java Developer's Guide: