How to draw shapes using Graphics

By | 2017-11-23T01:47:35+00:00 November 23rd, 2017|java|0 Comments

In this tutorial I am going to show you how to draw shapes using Graphics in Java. Graphics is a 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 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.

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) {
        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);
            case 2:
                g.drawOval(10+i*10, 10+i*10, 50+i*10, 50+i*10);
    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.setSize(300, 300);

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:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment