Draw a 2D Rectangle in Java

We will learn how to draw a 2D rectangle in Java in this article.

Java allows us to draw 2D objects using the Graphics class. The graphics class is a part of AWT. The AWT in Java is an application programming interface that creates a graphical user interface. Since we want to draw a 2D rectangle, we only need to import the Dimension and Graphics class from the AWT package. We will also import the javax.swing class which allows us to use JPanel. JPanel is a container that stores a group of components and is used for organizing various layouts. It displays the final output.

See the following code.

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class Rectangle extends JPanel {
    private static final int RCT_X = 20;
    private static final int RCT_Y = RCT_X;
    private static final int RCT_WIDTH = 100;
    private static final int RCT_HEIGHT = RCT_WIDTH;

    protected void paint_Component(Graphics g) {
        // draw the rectangle here
        g.drawRct(RCT_X, RCT_Y, RCT_WIDTH, RCT_HEIGHT);

    public Dimension get_Preferred_Size() {
        // so that our GUI is big enough
        return new Dimension(RCT_WIDTH + 2 * RCT_X, RCT_HEIGHT + 2 * RCT_Y);

    // create the GUI explicitly on the Swing event thread
    private static void create_And_Show_Gui() {
        Rectangle mainPanel = new Rectangle();

        JFrame frame = new JFrame("Rectangle");
    public static void main(String[] args) {


draw rectangle in java

In the above code, we can see our 2D rectangle being shown in the JPanel. The Rectangle class is extended to JPanel. Here we have initialized the length and breadth of the rectangle. The paint_component() method draws the rectangle. The create_And_Show_Gui() method is used to create GUI and set the display frame on which the final output is printed.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.