Posted By:
20 Feb, 2014 1:16 pm PST

How to draw polygon in Java ?

Write a program to create a polygon that is filled with black color. This polygon must be created inside a rounded rectangle which is filled with pink color.

import java.awt.*;

import java.awt.event.*;

public class DrawPoly extends Frame {

       public static void main(String[] args) {

              DrawPoly h = new DrawPoly();




              h.addWindowListener(new WindowAdapter()


                     public void windowClosing(WindowEvent e)






public void paint(Graphics c)


       //set pink color


       //display a filled rounded rectangle

       c.fillRoundRect(30, 30, 250, 250, 30, 30);

       //set black color


//take x and y as coordinates in arrays

       int x[]={40,200,40,100};

       int y[]={40,40,200,200};

    //there are 4 pairs of x,y coordinates

       int num=4;

       //create filled polygon connecting the coordinates








Java.awt : Contains all of the classes for creating user interfaces and for painting graphics and images.

Frame class : A Frame is a top-level window with a title and a border.

public class Frame

extends Window

implements MenuContainer

WindowListener Interface: The listener interface for receiving window events. The class that is interested in processing a window event either implements this interface (and all the methods it contains) or extends the abstract WindowAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a Window using the window's addWindowListener method. When the window's status changes by virtue of being opened, closed, activated or deactivated, iconified or deiconified, the relevant method in the listener object is invoked, and the WindowEvent is passed to it.

Paint function() :  This method will be invoked when it is time to paint. This method will be executed by the painting subsystem whenever you component needs to be rendered. Its signature is:

  • public void paint(Graphics g)


Was it useful?  

Please login to reply to this problem.