working with Graphics

The AWT supports a rich assortment of graphics method.All graphics are drawn reative to window.This can be a main wi ndow of an applet,a child window of an applet ,or stand alone appliction of window.The origin of each window is at the top-left corner and is 0,0. Coordinates are specified in pixels. All output to a window takes place through a graphics context. 

A graphics context is encapsulated by the Graphics class and is obtained in two ways:

• It is passed to a method, such as paint( ) or update( ), as an argument.

• It is returned by the getGraphics( ) method of Component.

The Graphics class defines a number of drawing functions.Each shape can be drawn edge only or filled .several drawing methods are:

  • Drawing Lines

      Lines are drawn by means of the drawLine() method,shown here:

                               void drawLine(int startX,int startY,int endX,int endY)

simple applet program to drawn a line


import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet
 {
   int width, height;
   public void init()
 {
      width = getSize().width;
      height = getSize().height;
      setBackground( Color.black );
   }
   public void paint( Graphics g ) 
{
      g.setColor( Color.green );
      for ( int i = 0; i < 10; ++i ) 
{
         g.drawLine( width, height, i * width / 10, 0 );
      }
   }
}


Sample output from this program is shown here:



















No comments:

Post a Comment