How do I draw a rectangle in Java 2D?

The code snippet below show you how to use the Graphics2D class the draw a rectangle. You can see the snippet in the paintComponent(Graphics g) method defined in the anonymous JPanel object.

To draw a rectangle we use the Rectangle2D.Double static-inner class. The constructor of this class accept the information about the rectangle x, y coordinates and its witdh and height.

Here is the result you’ll get when you run the snippet:

Draw Rectangle Demo

  • Rejith Egodahewa

    I may need your help time to time to explore Java Graphics…
    there are things to be understood..


    Sri Lanka