How to draw a circle in Java – GUI

In this tutorial, you will learn about how to draw a circle using GUI in Java.

Before continuing make sure you go through the article below:

Introduction to GUI Build first GUI Application in Java using NetBeans IDE

Firstly you need to import packages which are:-   javax.swing.JFrame for creating a working window space and java.awt.Graphics for all the graphics which allow the application to draw the shapes.

After import creates a class in which JFrame is inherited and a constructor.

import java.awt.Graphics;
import javax.swing.JFrame;

public class CircleInGUI extends JFrame{
   
public CircleInGUI()
{

 super("Circle In GUI");

 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 setSize(400,400);

 setVisible(true);
}

super ()  used to set the title in JFrame

setDefaultCloseOperation() used to set the default closing of the JFrame.

setSize() used to set the size of JFrame.

setVisible() used to set the visibility mode of the JFrame.

 Calling and overriding the method paint() in Java

This method is used to give access to the Graphics class. Using the object of the graphic class, we will then call drawOval()

public abstract void fillOval(int a, int b, int width, int height)

This is used to draw the oval of the required width and height. Here, in this case, we want to draw a circle so we will make sure that the width and height given are the same to get the accurate output. Finally, make the main class and create the object of the class CircleInGUI 

public void paint(Graphics gh)
   {
      super.paint(gh);
      //draw circle outline
      gh.drawOval(80,80,150,150);
   }

public static void main(String[]args)
  {
     CircleInGUI  obj =new CircleInGUI();
   }
}

OUTPUT

How to draw a circle in Java - GUI

Hope you gained something, Keep Learning !!

Leave a Reply

Your email address will not be published.