/* * Drawing.java 1.0 * * Classes for lecture 2. * The only thing to concentrate on is the tree method * in class Drawing, and the clone method of class Pen. * The clone method is used in one of the exercises. */ import javax.swing.*; import java.awt.*; public class Drawing { public static void main(String args[]) { System.out.println("Starting Drawing..."); MyFrame mainFrame = new MyFrame(); /* Wait a second before drawing, to make sure the * window is really in the front of all other windows */ try{Thread.sleep(1000);}catch(Exception e){}; /* Make a pen on the main window, and * locate the pen at the center bottom, pointing * upwards */ Pen p = mainFrame.makePen("Blue"); p.turn(180); p.jumpTo(180,350); /* draw a tree 50 pixels height */ tree(p,60); } private static void tree(Pen p, int height){ if (height < 2 ) return; p.move(height); Pen leftTree = (Pen)p.clone(); leftTree.turn(30); Pen rightTree = (Pen)p.clone(); rightTree.turn(-45); tree(leftTree,height-10); tree(rightTree, height-5); } } class MyFrame extends JFrame { MyFrame(){ super(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setTitle("Drawing"); setVisible(true); } Pen makePen(String color){ return new Pen(color,this); } } class Pen implements Cloneable { private int x,y; private double heading; private final Component myComponent; private Color col; public Pen(String color, Component c){ myComponent = c; x = c.getWidth()/2;// middle of component y = c.getHeight()/2; if ( color.equals("Red") ) col = Color.RED; if ( color.equals("Green") ) col = Color.GREEN; if ( color.equals("Blue") ) col = Color.BLUE; } public void jumpTo(int newX, int newY){ x = newX; y = newY; } public void moveTo(int newX, int newY){ Graphics g = myComponent.getGraphics(); g.setColor(col); g.drawLine((int)x,(int)y,(int)newX,(int)newY); x = newX; y = newY; } public void move(int length){ int dX = (int)Math.round(length*Math.sin(Math.toRadians(heading))); int dY = (int)Math.round(length*Math.cos(Math.toRadians(heading))); moveTo(x+dX, y+dY); } public void turn(double angleChange){ heading = (heading + angleChange) % 360; } public String toString(){ return "["+x+","+y+"("+heading+")]"; } public Object clone(){ try{ Pen c = (Pen)super.clone(); return c; //super.clone(); }catch(CloneNotSupportedException e) { throw new RuntimeException("super class doesn’t implement cloneable"); } } }