// マンデルブロート集合
import java.applet.* ;
import java.awt.* ;
import java.awt.event.* ;

public class demo02 extends Applet implements ActionListener {
  double realMin   = -2.2 ;
  double realMax   =  0.5 ;
  double imageMin  = -1.35 ;
  double imageMax  =  1.35 ;
  int    maxIter   =  500 ;
  int    viewSize  =  500 ; 
  int    divFactor =  (int)(viewSize*1.2) ;
  Color[] pal = {
    new Color(255,  0,  0),
    new Color(  0,255,  0),
    new Color(255,255,  0),
    new Color(  0,  0,255),
    new Color(255,  0,255),
    new Color(  0,255,255),
    new Color(255,255,255) } ;
  TextField box1 = new TextField(5) ;
  TextField box2 = new TextField(5) ;
  TextField box3 = new TextField(5) ;
  TextField box4 = new TextField(5) ;
  Button    go   = new Button("再描画") ;

  void setPixel(Graphics g,double x,double y,int c) {
    int ix, iy ;
    ix = (int)((x-realMin)*(double)viewSize/(realMax-realMin))+30 ;
    iy = viewSize+30-(int)((y-imageMin)*(double)viewSize/(imageMax-imageMin)) ;
    g.setColor( pal[c] ) ;
    g.fillOval(ix,iy,1,1) ;
  }

  public void init() {
    resize(viewSize+60,viewSize+60) ;
    add(new Label("実部 min:",Label.RIGHT)) ;
    add(box1) ; box1.setText(Double.toString(realMin)) ; 
    add(new Label(" max:",Label.RIGHT)) ;
    add(box2) ; box2.setText(Double.toString(realMax)) ; 
    add(new Label(" 虚部 min:",Label.RIGHT)) ;
    add(box3) ; box3.setText(Double.toString(imageMin)) ; 
    add(new Label(" max:",Label.RIGHT)) ;
    add(box4) ; box4.setText(Double.toString(imageMax)) ; 
    add(go) ; go.addActionListener(this) ;
  }

  public void actionPerformed(ActionEvent e) {
    if( e.getSource() == go ) {
      String p ;
      p = box1.getText() ; realMin = Double.valueOf(p).doubleValue() ;
      p = box2.getText() ; realMax = Double.valueOf(p).doubleValue() ;
      p = box3.getText() ; imageMin = Double.valueOf(p).doubleValue() ;
      p = box4.getText() ; imageMax = Double.valueOf(p).doubleValue() ;
      repaint() ;
    }
  }

  public void paint(Graphics g) {
    int ir, ii ;
    g.setColor(Color.black) ;
    g.fillRect(30,30,viewSize,viewSize) ;
    for( ir=0 ; ir<=divFactor ; ir++ ) {
      double x = realMin+(realMax-realMin)*ir/(double)divFactor ;
      for( ii=0 ; ii<=divFactor ; ii++ ) {
        double y = imageMin+(imageMax-imageMin)*ii/(double)divFactor ;
        int c = 0 ;
        double realPart=0, imagePart=0 ;
        double r, i ;
        while( c<maxIter ) {
          c++ ;
	  if( realPart*realPart+imagePart*imagePart>4 ) {
	    setPixel(g,x,y,c%7) ;
	    break ;
	  }
          r = realPart*realPart - imagePart*imagePart + x ;
          i = 2*realPart*imagePart + y ;
          realPart = r ;
          imagePart = i ;
        }
      }
    }
  }
}