Animated Graph Drawing using Java2D

Hi,

I’m not sure if this post should be in the newless cluebies section, but here goes.

I have read (and, I think, understood) the whole article on “Painting in AWT and Swing” at http://java.sun.com/products/jfc/tsc/articles/painting/index.html

I am writing an app that needs to draw a graph (a mathematical one - nodes, edges etc). The graph will be changing rapidly so the drawing needs to be animated. I plan on using Java2D for this.

I was just wondering if someone could post a basic class structure for doing this. i.e. Should I extend JPanel or Component? Should I use paintImmediately() or will repaint() suffice?

Also how should I thread the actual algorithm that manipulates the graph so that when the algorithm is running, the GUI can still be used. Should I put the algorithm in its own class implementing Runnable?

Any design patterns that you guys commonly use? e.g. Model, View, Controller?

Thanks.

Just my idea, in 3 clases Painter(JPanel, Canvas), App(the algorithm, application) and Graph(the graph to be displayed).

First Painter.java


class Painter extends Canvas{
  Graph theGraph;
  public void setGraph(Graph g){
    theGraph = g;
  }
  public void paint(Graphics g){
    theGraph.drawIn(g);
  }
}

Second the Application.java


class Application implements Runnable{
  Graph gr;
  Painter painter;
  public Application(Painter p){
    painter = p;
    //your init code
    painter.setGraph(gr);
  }
  public void run(){
    //your algorithm code
    painter.repaint();
    //maybe a Thread.sleep()...
  }
  public static void main(String[] args){
    Painter pa = new Painter();
    Application app = new Application(pa);
    //Put the Painter in a Frame and display it
    Thread t = new Thread(app);
    t.start();
  }
}

For the Graph, it must have a method drawIn(Graphics g) where the graph draws the nodes and edges.

You must finish the code to take out the flickering it will produce (no double buffer).

Rafael.

There is an animated graph in the JDK samples.

Additionally, I’d like to guide your interest to the libs jazz and picollo http://www.cs.umd.edu/hcil/jazz/ that you might find helpful.

We created a graph lib in top of jazz easily.

Thanks a lot for the replies.

Rafael, your code structure is quite interesting. I didn’t end up implementing it exactly the way you described, but for my next project I think I might give your structure a try. My program actually turned out quite well. I basically Had a Model.java and a View.java and a seperate class extending JPanel in which I overwrote the paintComponent(Graphics g) method. I will post the full structure up for criticism when I get the time (my uni lecturers are slave drivers at the moment).

Jazz also sounds very interesting.

Ahh, Java never ceases to amaze me with its incredible depth of quality packages and support for so many different APIs. Java kicks.