In this tutorial, I am going to show you how to draw shapes using Graphics in Java. Graphics is an abstract base class for all graphics contexts.  This class allows us to draw on components.

Draw shapes using Graphics :

For this example, I am going to draw Rectangles and Ovals on the JPanel component.

drawRect() : This method allows us to draw a rectangle with a specific/given dimensions.

drawOval() : This method allows us to draw oval with given dimensions.

DrawShapes.java
package com.onlinetutorialspoint.swing;

import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class DrawShapes extends JPanel {
    private int input;

    public DrawShapes(int choice) {
        input = choice;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < 10; i++) {
            switch (input) {
            case 1:
                g.drawRect(10+i*10, 10+i*10, 50+i*10, 50+i*10);
                break;
            case 2:
                g.drawOval(10+i*10, 10+i*10, 50+i*10, 50+i*10);
                break;
            }
        }
    }
    public static void main(String[] args) {
        String choice = JOptionPane.showInputDialog("Enter 1 to draw rectangles \n"+"Enter 2 to draw Ovals");
        DrawShapes shapes = new DrawShapes(Integer.parseInt(choice));
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(shapes);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

Output :

draw shapes using Graphics 1

Draw Rectangles :

draw shapes using Graphics 2

Selecting Ovals :

draw shapes using Graphics 3-

Draw Ovals :

draw shapes using Graphics 4

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment