What is drawpolygon() in Java?

Share

Overview

A polygon is a closed plane figure consisting of line segments joining more than one vertices.

The drawpolygon() method is a method of the Graphics class in Java that is used to draw polygons.

Syntax

drawpolygon(int[] x, int[] y, int numberOfPoints)
  • int[]x: It is an integer array consisting of x-coordinates of the required shape.

  • int[]y: It is an integer array consisting of y-coordinates of the required shape.

  • int numberOfPoints: It is an integer variable used to declare the number of vertices the figure will have.

Example

import java.awt.*;
import javax.swing.*;

class Main extends JPanel {
    public void paintComponent(Graphics g) {
        int [] x = {45, 55, 75, 55, 63, 43, 17, 31, 12, 35, 45};
        int [] y = {41, 65, 71, 83, 108, 88, 105, 78, 61, 63,41};
        g.drawPolygon(x, y, 10); // 10 vertices required to draw a star
    }

    public static void main( String args[] ) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Draw Polygon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.white);
        frame.setSize(300, 200);

        Main panel = new Main();

        frame.add(panel);

        frame.setVisible(true);
    }
}

Explanation

  • Line 1: We import the AWT API for making a GUI.

  • Line 2: We import the Swing API for making a GUI.

  • Line 4: We create a class and inherit it from JPanel.

  • Line 5: We override the paintComponent() method of JPanel class.

  • Line 6: We make an array of x-coordinates of points to draw a star.

  • Line 7: We make an array of y-coordinates of points to draw a star.

  • Line 8: We call the built-in drawPolygon() method of Graphics class to draw a star. It takes three parameters as array of x-coordinates, array of y-coordinates and total number of points of the shape drawn, respectively .

  • Line 11: We override the main() method.

  • Line 12: Let the System handle the decoration (the borders) of the window. Using this, the window appeared will be a decorated one with fancy borders. This line is optional.

  • Line 13: We create an object of JFrame to create the window and set its name as “Draw Polygon”.

  • Line 14: This causes the window to close on receiving a close window event.

  • Line 15:We set the background color as white. This is optional.

  • Line 16: We set the window size.

  • Line 18: We create an object of Main class. It will automatically call the paintComponent() method (the one which we have to override).

  • Line 20: We add this component (the drawn polygon) into the window.

  • Line 22: We make the window visible by setting the flag to true.