Draw a Polygon in Java Applet
Last Updated :
08 May, 2018
Polygon is a closed figure with finite set of line segments joining one vertex to the other. The polygon comprises of set of (x, y) coordinate pairs where each pair is the vertex of the polygon. The side of the polygon is the line drawn between two successive coordinate pairs and a line segment is drawn from the first pair to the last pair.
We can draw Polygon in java applet by three ways :
- drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the given set of x and y points.
import java.awt.*;
import javax.swing.*;
public class poly extends JApplet {
public void init()
{
setSize( 200 , 200 );
show();
}
public void start()
{
}
public void stop()
{
}
public void paint(Graphics g)
{
int x[] = { 10 , 30 , 40 , 50 , 110 , 140 };
int y[] = { 140 , 110 , 50 , 40 , 30 , 10 };
int numberofpoints = 6 ;
g.setColor(Color.blue);
g.drawPolygon(x, y, numberofpoints);
}
}
|
Output :
- drawPolygon(Polygon p) : draws a polygon with the given object of Polygon class.
import java.awt.*;
import javax.swing.*;
public class poly extends JApplet {
public void init()
{
setSize( 200 , 200 );
show();
}
public void start()
{
}
public void stop()
{
}
public void paint(Graphics g)
{
int x[] = { 10 , 30 , 40 , 50 , 110 , 140 };
int y[] = { 140 , 110 , 50 , 40 , 30 , 10 };
int numberofpoints = 6 ;
Polygon p = new Polygon(x, y, numberofpoints);
g.setColor(Color.blue);
g.drawPolygon(p);
}
}
|
Output :
- drawLine(int x, int y, int x1, int y1) : In this method we would connect adjacent vertices with a line segment and also connect the first and last vertex.
import java.awt.*;
import javax.swing.*;
public class poly extends JApplet {
public void init()
{
setSize( 200 , 200 );
show();
}
public void start()
{
}
public void stop()
{
}
public void paint(Graphics g)
{
int x[] = { 10 , 30 , 40 , 50 , 110 , 140 };
int y[] = { 140 , 110 , 50 , 40 , 30 , 10 };
int numberofpoints = 6 ;
g.setColor(Color.blue);
for ( int i = 0 ; i < numberofpoints - 1 ; i++)
g.drawLine(x[i], y[i], x[i + 1 ], y[i + 1 ]);
g.drawLine(x[ 0 ], y[ 0 ], x[numberofpoints - 1 ], y[numberofpoints - 1 ]);
}
}
|
Output :
Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...