Writing General Graphics Programs

When an applet starts executing, paint( Graphics g ) is automatically called. It paints the screen. If you want other methods to produce graphics, you must pass the parameter g2 to them from paint. For instance to call method begin(), you include begin( g2) in paint and then write the method heading as public void begin( Graphics2D g2). Once the screen is painted, if you want to change the background to a random color, or move an image randomly, you cannot repaint it in paint.One way of getting around this is to call another method, say begin() and then call paint from there. This is done by including the statement repaint() in method begin(). In cases like that, you would set up your class as described in the following psuedocode, where count indicates how many times the process should be done (it is used in the if in begin(), taking the place of the for loop you are accustomed to seeing in paint():

public class Example
{ int count;
  final int LIMIT = 100;
  declare other instance variables;
  
  public init()
  { count = 0;
    initialize other instance variables; 
  }

  public void paint(Graphics g)
  { ...;
    begin(g2)
  }
  
  public void begin( Graphics2D g2)
  {  count++;
     if(count < LIMIT)
     { perfom your graphics;
       pause();
       repaint();
     }
  }

}
     

If a limit had not been placed on count then the program would have peformed an infite loop. Also, initializing count in paint() would cause an infinite loop. Each time the screen is repainted, all previous images are erased.