/* * Created on Jul 18, 2004 */ package treeDraw; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; /** A simple frame and panel for displaying an IDrawableNode. * Use the setTree method to place your tree inside the frame. * See the main method for an example of how to use. * * @author dickey */ public class TreeDrawFrame extends JFrame { public static final int PANEL_WIDTH = 600; public static final int PANEL_HEIGHT = 500; private TreeDrawPanel treePanel; public TreeDrawFrame() { super("Tree Draw Frame"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contents = getContentPane(); this.treePanel = new TreeDrawPanel(); contents.add(treePanel); pack(); show(); } public void setTree(IDrawableNode tree) { this.treePanel.setTree(tree); } /** A panel which contains a tree which is drawn. */ private class TreeDrawPanel extends JPanel { public TreeDrawPanel() { setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); setBackground(Color.WHITE); } private IDrawableNode theTree; public void setTree(IDrawableNode tree) { this.theTree = tree; this.repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); //don't forget this! Or background is not cleared. if (this.theTree != null) { this.theTree.paint(this, (Graphics2D) g, 0, 0); } } } /** An example of how to create and use the frame. * This won't compile until you replace "GraphingNode" and/or * "DrawableTree" with your own * class implementing IDrawableNode. * @param args not used */ public static void main(String[] args) { final TreeDrawFrame tframe = new TreeDrawFrame(); tframe.setTitle("Tree Demo"); GraphingNode testNode = GraphingNode.randomNode(30); IDrawableNode testTree = new DrawableTree(testNode); tframe.setTree(testTree); //the tree should now be displayed // Following illustrates a framework for animation. // Not needed until the second week! class AnimationThread extends Thread { public void run() { final int delay = 1000; //milliseconds final int maxNodes = 200; final int maxTrees = 500; Random rand = new Random(); for (int sec = 0; sec < maxTrees; sec++) { try { Thread.sleep(delay); } catch (InterruptedException e) { break; } int howManyNodes = rand.nextInt(maxNodes); GraphingNode testNode = GraphingNode.randomNode(howManyNodes); IDrawableNode testTree = new DrawableTree(testNode); tframe.setTree(testTree); //show another tree } } //end run }; AnimationThread animator = new AnimationThread(); animator.start(); //starts the animation } }