/* ------------------------------------------------------------------------- File: PocketSpiroGraph.java Author: David R. Chung dchung@soli.inav.net http://soli.inav.net/~dchung ------------------------------------------------------------------------- */ import java.awt.*; import java.awt.Color; import java.lang.Math ; public class PocketSpiroGraph extends java.applet.Applet // applet base class { Button startButton ; DrawingPanel drawingPanel ; public void init() { resize(200,225); setLayout( new BorderLayout()) ; startButton = new Button( "New Image" ) ; drawingPanel = new DrawingPanel() ; add( "Center", drawingPanel ) ; add( "South", startButton ) ; drawingPanel.newSpirograph() ; } public boolean handleEvent(Event evt) { if("New Image".equals(evt.arg)) { drawingPanel.newSpirograph() ; return true ; } return false ; } } class DrawingPanel extends Panel { Dimension q = size(); PolarPlot graph = new PolarPlot( 5, 5, 190, 1.0 ) ; double a, b, c ; public void init() { a = Math.round(Math.random()*1000) ; b = Math.round(Math.random()*1000) ; c = Math.round(Math.random()*1000) ; } public void newSpirograph() { a = Math.round(Math.random()*1000) ; b = Math.round(Math.random()*1000) ; c = Math.round(Math.random()*1000) ; repaint() ; } public void paint(Graphics g) { Dimension d = size(); g.setColor( new Color( 229,215, 144 ) ) ; g.fillRect(0,0, d.width - 1, d.height - 1); g.setColor( Color.black ) ; g.drawRect(0,0, d.width - 1, d.height - 1); for ( double theta = 0.0; theta < 360.0;theta += 0.02 ) { graph.Plot( g, Math.sin( a * theta ) * Math.cos( b * (theta + c) ), theta, Color.red ) ; } } } class PolarPlot { int m_UpperLeftX ; int m_UpperLeftY ; int m_Width ; int m_OriginX ; int m_OriginY ; double m_ScaleFactor ; int m_OffsetX ; int m_OffsetY ; public PolarPlot( int upperLeftX, int upperLeftY, int width, double maxR ) { m_UpperLeftX = upperLeftX ; m_UpperLeftY = upperLeftY ; m_Width = width ; m_OriginX = upperLeftX + width / 2 ; m_OriginY = upperLeftY + width / 2 ; m_ScaleFactor = (double)width / ( 2.0 * maxR ) ; m_OffsetX = upperLeftX + width / 2 ; m_OffsetY = upperLeftY + width / 2 ; } public void Plot( Graphics g, double r, double theta, Color color ) { g.setColor( color ) ; int x = (int)( m_ScaleFactor * r * Math.cos( theta ) ) + m_OffsetX ; int y = (int)( m_ScaleFactor * r * Math.sin( theta ) ) + m_OffsetY ; g.drawLine( x, y, x, y ) ; } }