How to draw Rectangle in Java Applet

Rectangle can be drawn by using drawLine() method. With this method, only the outline of the rectangle is drawn using Graphics object(Graphics gra)color but of the rectangle is not filled with this color. To draw a filled rectangle, the graphics class provide the fillRect() method.

 

import java.awt.*;

import java.applet.Applet;

public class Rectangle extends Applet //Rectangle is the name of the class

   {

     public void paint(Graphics gra) //paint() is used to draw rectangles

     {

         setBackground(Color.gray);

       int insett;   // Gap between borders of applet and one of the rectangles.

                  

       int rectWidthh, rectHeightt;   // size of one of the rectangles.

                  

       gra.setColor(Color.pink);

       gra.fillRect(0,0,300,160); // Fill the entire applet with pink.

    

     gra.setColor(Color.black); // Draw the rectangles in black.

                                      

     insett = 0;

     rectWidthh = 299;   // Set size of first rect (according to size of applet)

     rectHeightt = 159;

    

       while (rectWidthh >= 0 && rectHeightt >= 0)

           {

             gra.drawRect(insett, insett, rectWidthh, rectHeightt);

             insett += 15;       // Rects are 15 pixels apart.

           rectWidthh -= 30;   // Width decreases by 15 pixels (from left) and 15(from right)

                                        

           rectHeightt -= 30; // Height decreases by 15 pixels (on top) and 15(on bottom)

                          

           }

    } // end paint() method

}

//<applet code="Rectangle.class" height=500 width=500></applet>

draw rectangle in java

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @