Java Program to Draw a Line Using GUI

«
»

This is a Java Program to Draw a Line Using GUI

Problem Description

We have to write a program in Java such that it creates a line with random co-ordinates in an applet.

Expected Input and Output

For drawing a line, we can have the following set of input and output.

advertisement

To Draw a Line :

On every execution of the program, 
it is expected that a line with random co-ordinates is drawn.
Problem Solution

1. Create a class and inherit the Applet class.
2. Generate four random integers x1, y1, x2, and y2 which lie within the bounds of the frame.
3. Draw a line from (x1,y1) to (x2,y2).

Program/Source Code

Here is source code of the Java Program to draw a line. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

advertisement
  1. /* Java Program to Draw a Line using GUI */
  2. import java.applet.*;
  3. import java.awt.*;
  4. import java.lang.Math;
  5. public class Line extends Applet
  6. {
  7.     //Function to initialize the applet
  8.     public void init()
  9.     {
  10. 	setBackground(Color.white);
  11.     }
  12.     //Function to draw the line
  13.     public void paint(Graphics g)
  14.     {
  15. 	int x1 = (int)(Math.random()*1000)%500;
  16. 	int y1 = (int)(Math.random()*1000)%500;
  17.  
  18. 	int x2 = (int)(Math.random()*1000)%500;
  19. 	int y2 = (int)(Math.random()*1000)%500;
  20.  
  21. 	g.drawLine(x1,y1,x2,y2);
  22.     }
  23. }
  24. /*
  25. <applet code = Line.class width = 500 height = 500>
  26. </applet>
  27. */

To compile and execute the program use the following commands :

>>> javac Line.java
>>> appletviewer Line.java
Program Explanation

1. The method Math.random of the Math class generates a random number between 0 and 1.
2. The method drawLine(x1,y1,x2,y2) of the Graphics class is used to draw a line from (x1,y1) to (x2,y2).

Runtime Test Cases

Here’s the run time test cases to draw a line for different input cases.

advertisement

Test case 1 – To View a Line.
java-applet-draw-line-1

Test case 2 – To View a Line.
java-applet-draw-line-2

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn