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.

package org.kodejava.example.awt.geom;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class DrawRectangle {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Draw Rectangle");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.add(new JPanel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        //
                        // Draw a rectangle using Rectangle2D class
                        //
                        Graphics2D g2 = (Graphics2D) g;
                        g2.setColor(Color.RED);

                        double x = 100;
                        double y = 100;
                        double width = x + 200;
                        double height = y + 50;
                       
                        //
                        // Draw the red rectangle
                        //
                        g2.draw(new Rectangle2D.Double(x, y, width, height));

                        g2.setColor(Color.BLUE);
                        //
                        // Draw the blue rectangle
                        //
                        g2.draw(new Rectangle2D.Double(150, 50, 200, 250));
                    }
                }, BorderLayout.CENTER);

                frame.pack();
                frame.setSize(new Dimension(500, 400));
                frame.setVisible(true);
            }
        });
    }
}

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

Draw Rectangle Demo

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

1 Comments

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

    Rejith

    Sri Lanka

Leave a Reply