CJCoding With Joseph
15free / daySign inCreate account

Mastering Java Swing

Drawing Squares

Java Swing Drawing Shapes

To draw shapes like squares in Swing, we use the paintComponent method. This method allows us to define how components are visually rendered inside a panel. Here's how to create a simple program that draws a square.

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

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Drawing a Square");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g); // Clears the panel for fresh drawing
                g.setColor(Color.BLUE);  // Set the drawing color to blue
                g.fillRect(50, 50, 100, 100); // Draw a square at (50, 50) with size 100x100
            }
        };

        frame.add(panel); // Add the panel to the frame
        frame.setVisible(true); // Make the frame visible
    }
}
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.