Monday , December 11 2017
Home / java / How to draw shapes using Graphics

How to draw shapes using Graphics

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) {
        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 chandrashekhar

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+ ,

Recommended

Java Graphics2D Class Example

In this tutorials, we are going to see how to use Java Graphics2D class. Java …

Leave a Reply

Your email address will not be published. Required fields are marked *