Setting the Pen on a Graphics Object

The Pen object itself contains no coloring or drawing capability. It only describes a subset of the capabilities of the GDI. Before you use a Pen to draw on a form, you associate the Pen with a Graphics object using the Graphics object's setPen method:

Graphics g = this.createGraphics();
g.setPen(new Pen(PenStyle.DASH));

After you associate a Pen with a Graphics object, all lines drawn within the Graphics object's bounding rectangle are drawn using that pen. In addition, you can call the setPen method any number of times on the same Graphics object.

The following example demonstrates how the Pen object works with the line-drawing capabilities of the Graphics object. In this example, the Pen styles defined in the Pen object are stored in an array of integers. Within the class's paint event handler, a for loop is used to iterate through this array of pen styles, drawing a single line using each style:

public class Form1 extends Form
{
   
int [] rgStyles = { PenStyle.DASH, PenStyle.DASHDOT, PenStyle.DASHDOTDOT,
                  PenStyle.DOT, PenStyle.INSIDEFRAME, PenStyle.SOLID };

   protected void onPaint(PaintEvent e)
   {
      Rectangle rc = this.getClientRect();
      
      rc.y += 10;
      
      for(int i = 0; i < rgStyles.length; i++){
         
         e.graphics.setPen(new Pen(Color.BLACK, i));
         e.graphics.drawLine(new Point(0, rc.y),
                        new Point(rc.width, rc.y));
         
         rc.y += 10;
      }
   }

// Rest of Form1 class...