Lines

To draw a line on the screen you call the drawLine method available in the Java Graphics class. The drawLine method requires four numerical arguments. The first pair of numbers represent the coordinates in pixels (within the applet window) of the first endpoint of the line segment. The second pair of numbers are the coordinates of the second endpoint. If either endpoint is outside the applet window, the line is clipped to fit the defined window.

The applet shown below illustrates the use of twelve lines in various colors to paint a message in the defined applet window.

   
 

View Code

There is no thickness property for lines. The following applet demonstrates how you can use a for loop to paint multiple lines to create the illusion of one thick line.

   
 

 

The code for this Java line applet is listed below.

 

import java.awt.Graphics;
import java.awt.Color;


public class lines2 extends 
java.applet.Applet {



  public void paint(Graphics g) {
	int i;
	int j;
	int k;
	j=10;
	k=280;
	g.setColor(Color.blue);
	for (i=1;i<10;i++){
    	    	g.drawLine(10,j,280,k);
		j=j+1;
		k=k+1;
				}
       }
}
This allows us to use the Graphics methods of the Java Abstract Windowing toolkit.

We want to generate an applet .


The paint method is the way an applet draws objects on the screen. Three integers are declared and two of them are
initialized.

Set the color to blue.
Using a for loop, draw the line 9 times, incrementing the
vertical coordinate of each endpoint one pixel for each pass.

 

After compiling this program we need to create an HTML page with a reference to the class file. It must run in a graphic window that is large enough to accomodate the pixels in the applet.

Save the HTML code in the same directory as the class file.

When you load the HTML file in your browser the applet will execute within the window.

Go to the next topic: Rectangles

Back to the Table of Contents