How to draw a rectangle in Java?

To draw a rectangle in Java, call the Graphics.drawRect method inside JFrame.paint.

Here is the smallest amount of code to draw a rectangle in Java:

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

public class DrawRectangle extends JFrame {

  @Override
  public void paint(Graphics graphics) {
    graphics.drawRect(100, 100, 200, 200);
  }

  public static void main(String[] args) {
    DrawRectangle frame = new DrawRectangle();
    frame.setSize(500, 500);
    frame.setVisible(true);
  }
}

This program creates a 500x500 window (JFrame), that paints a 200x200 rectangle inside of itself.