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.
graphics.fillPolygon(xPoints,yPoints,nPoints)
It fills the polygon for the given array of x
and y
coordinates.
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); } }
In the code above:
red
.fillPolygon()
method, it fills with current graphics context color.