Zain Zafar
Zain Zafar

Reputation: 1607

How to create a ring using drawOval()?

I am new to Java. I am creating a thick ring in a applet. I am using drawOval method in a for loop. This creates multiple rings but that are not centered. Please check the image and help me as soon as possible!

non-centered rings

Upvotes: 0

Views: 806

Answers (3)

APan
APan

Reputation: 366

As you know the ellipse drawn is within a bounding rectangle, you can use something like this. This is for 7 concentric circles. You can customize the the distance, decide whether they are growing concentric circles or shrinking concentric circles, the number of circles by changing the for loop conditions.

import java.awt.*;;
import java.applet.*;

/*
<applet code="Ellipses" width=400 height=400>
</applet>
*/

public class Ellipses extends Applet
{
    public void paint(Graphics g)
    {
        int i,j,k,l;
        for(i=170,j=170,k=50,l=50;i>=110;i-=10,j-=10,k+=20,l+=20)
        g.drawOval(i,j,k,l);
    }
}

Upvotes: 0

Yuvraj Kakkar
Yuvraj Kakkar

Reputation: 1163

Here every ring you draw is centered but due to consecutive drawn ring it doesn't appear to be. Therefore you can use Mouse Pressed Event to draw or fill oval on each click.

    onMousePressed(Event e)
{
    Graphics g= getGraphics();
    g.fillOval(e.getX(),e.getY(),size,size);

}

Just observer and try .... your own logic.

Upvotes: 0

flaviut
flaviut

Reputation: 2143

You might be able to use fillOval() in order to avoid drawing many different ovals so that you only have to draw 2, one with the edge color and another with the background color. To center the oval, try something like fillOval(origX + changeInThickness / 2, origY + changeInThickness / 2, origWidth - changeInThickness, origHeight - changeInThickness)

Upvotes: 1

Related Questions