How to Draw a Circle in java
|

How to Draw a Circle in java

To draw a circle in Java, you can use the drawOval() method of the Graphics class. This method takes four arguments: the x and y coordinates of the upper-left corner of the bounding rectangle of the oval, and the width and height of the bounding rectangle. The circle will be drawn inside the bounding rectangle, with the center of the circle at the center of the rectangle.

Here is an example of how to use the drawOval() method to draw a circle in Java:

// Create a new Graphics object
Graphics g = ...

// Set the color to use when drawing the circle
g.setColor(Color.RED);

// Calculate the x and y coordinates of the upper-left corner of the bounding rectangle
int x = ...;
int y = ...;

// Calculate the width and height of the bounding rectangle
int width = ...;
int height = ...;

// Draw the circle
g.drawOval(x, y, width, height);

In this example, the drawOval() method is used to draw a circle with a red color. The coordinates and dimensions of the bounding rectangle are specified in the arguments of the method.

Note that the drawOval() method only draws the outline of the circle. If you want to fill the circle with a color, you can use the fillOval() method instead. This method works in the same way as the drawOval() method, but it fills the circle with the currently selected color instead of just drawing the outline.

For example, to fill a circle with the color blue, you can use the following code:

// Create a new Graphics object
Graphics g = ...

// Set the color to use when filling the circle
g.setColor(Color.BLUE);

// Calculate the x and y coordinates of the upper-left corner of the bounding rectangle
int x = ...;
int y = ...;

// Calculate the width and height of the bounding rectangle
int width = ...;
int height = ...;

// Fill the circle
g.fillOval(x, y, width, height);

In this example, the fillOval() method is used to fill the circle with a blue color. The coordinates and dimensions of the bounding rectangle are specified in the arguments of the method, just as with the drawOval() method.

Related articles:

Similar Posts

Leave a Reply

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