This is a Java Program to Draw a Line Using GUI
We have to write a program in Java such that it creates a line with random co-ordinates in an applet.
For drawing a line, we can have the following set of input and output.
To Draw a Line :
On every execution of the program, it is expected that a line with random co-ordinates is drawn.
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).
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.
/* Java Program to Draw a Line using GUI */
import java.applet.*;
import java.awt.*;
import java.lang.Math;
public class Line extends Applet
{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
}
//Function to draw the line
public void paint(Graphics g)
{
int x1 = (int)(Math.random()*1000)%500;
int y1 = (int)(Math.random()*1000)%500;
int x2 = (int)(Math.random()*1000)%500;
int y2 = (int)(Math.random()*1000)%500;
g.drawLine(x1,y1,x2,y2);
}
}
/*
<applet code = Line.class width = 500 height = 500>
</applet>
*/
To compile and execute the program use the following commands :
>>> javac Line.java >>> appletviewer Line.java
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).
Here’s the run time test cases to draw a line for different input cases.
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Java Internship
- Apply for Computer Science Internship
- Practice BCA MCQs
- Practice Information Technology MCQs
- Check Java Books