How to draw a tree representing a graph of connected nodes?
The simplest way I can think of is to write a class that extends JPanel
and override its paintComponent()
method. In the paint method you can iterate through the tree and paint each node. Here is a short example:
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JPanelTest extends JPanel {
@Override
public void paintComponent(Graphics g) {
// Draw Tree Here
g.drawOval(5, 5, 25, 25);
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.add(new JPanelTest());
jFrame.setSize(500, 500);
jFrame.setVisible(true);
}
}
Take a stab at painting the tree, if you can't figure it out post what you've tried in your question.
I'd say it's worth to check out Abego's TreeLayout too. It's essentially a tree layout algorithm so it can be used with any drawing mechanism, but it also contains some demos/examples of drawing graphs in SVG and Swing.
You might consider any of these:
JHotDraw, cited here, a meta-library for creating custom graph editors.
Prefuse visualization library, illustrated here and here.
Batik, which implements SVG rendering.
JGraph demo and user manual.
GraphStream, illustrated here.
JFreeChart
XYBubbleRenderer
A
JTree
, suggested here, with a customTreeIcon
.A custom renderer, with x based on a fraction of tree breadth and y based on recursion level.
A simple graph editor such as
draw.GraphPanel
, illustrated here.