Graphics Object Scope

The Graphics object has method scope. This means that when a method in which you use the Graphics object returns, the object’s dispose method is called automatically, freeing all resources that the object has allocated. After dispose has been called, attempts to use the object result in a run-time exception.

If you declare an instance of the Graphics object at the class level, you should use the Form object’s createGraphics method to initialize that object in every method that uses it:

Public class Form1 extends Form{

   Graphics g  = new Graphics();

   Private void Form1_resize(Object sender, Event e){
      
         // Initialize object instance.
         g = this.createGraphics();

         // dispose automatically called…
   }

   private void Form1_click(Object sender, Event e){

         // Initialize object instance.

         g = this.createGraphics();

         // dispose method automatically called…
   }
      

}

Although the dispose method is called automatically, it is good practice to call it explicitly at the end of routines that use the Graphics object. This is particularly important on the Windows 95 platform because of a system limitation on the number of device context that can be allocated.