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.setVisible(true);

              h.setTitle("Polygon");

              h.setSize(300,300);

              h.addWindowListener(new WindowAdapter()

              {

                     public void windowClosing(WindowEvent e)

                     {

                           System.exit(0);

                     }

              });

                     }

public void paint(Graphics c)

{  

       //set pink color

       c.setColor(Color.pink);

       //display a filled rounded rectangle

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

       //set black color

       c.setColor(Color.black);

//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

       c.fillPolygon(x,y,num);

       }

}

OUTPUT:

 

Attachment: workspace.zip


Description:

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.

Syntax: 
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)

 

Attachment: FilledPolygon.java
Was it useful?  




Please login to reply to this problem.