What is Graphics.fillPolygon() in Java?

Overview

The fillPolygon() method fills the given polygon. The Graphics class provides this method in the awt package.

It fills the polygon with present graphics context colour.

Syntax

graphics.fillPolygon(xPoints,yPoints,nPoints)

It fills the polygon for the given array of x and y coordinates.

Example

Let’s take a look at an example:

//import required packages
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

  public void paint(Graphics g) {

    //set graphics context color
    g.setColor(Color.red);

    
    int xpoints[] = {25, 145, 25, 145, 25};
    int ypoints[] = {25, 25, 145, 145, 25};
    int npoints = 5;
    
    //fill the polygon
    g.fillPolygon(xpoints, ypoints, npoints);
  }

  //main method
  public static void main(String[] args) {

    //Instantiate JFrame
    JFrame frame = new JFrame();

    //add panel
    frame.getContentPane().add(new Main());

    //Will exit the program when you close the gui
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //set width and height of the frame
    frame.setSize(200,200);

    //set visibility of the frame
    frame.setVisible(true);
  }
}

Explanation

In the code above:

  • Line 12: We set the color of the graphics to red.
  • Lines 15 to 17: We declare and initialize the coordinates and points for the polygon.
  • Line 20: We fill the polygon with the fillPolygon() method, it fills with current graphics context color.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources