I have developed a telecommunication application for locating signal strengths from the towers. I have used java swing and I'm having a problem when drawing the circle around the given point of the mobile signal transmitter tower location. I have already calculated the X, Y coordinates and also the radius value.
Please find the below code which I've used to draw the circle and it is having issues.
JPanel panelBgImg = new JPanel() { public void paintComponent(Graphics g) { g.drawOval(X, Y, r, r); } }
The issue is, it creates the circle but it didn't take the X and Y coordinates as the center point. It took the X and Y coordinates as the top left point of the circle.
Could anyone please help me to draw the circle by having the given X and Y coordinates as the center point of the circle.
Solution: Write a method, drawCircle() , which has parameters for the coordinates of the center point and a radius. It then calls drawOval with transformed parameters. To make a drawing, define a new component by subclassing JPanel and overriding the paintComponent() method.
9 Answers. Show activity on this post. The fillOval fits an oval inside a rectangle, with width=r, height = r you get a circle. If you want fillOval(x,y,r,r) to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.
In Java, the Graphics class doesn't have any method for circles or ellipses. However, the drawOval() method can be used to draw a circle or an ellipse. Ovals are just like a rectangle with overly rounded corners.
The fillOval
fits an oval inside a rectangle, with width=r, height = r
you get a circle. If you want fillOval(x,y,r,r)
to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.
public void drawCenteredCircle(Graphics2D g, int x, int y, int r) { x = x-(r/2); y = y-(r/2); g.fillOval(x,y,r,r); }
This will draw a circle with center at x,y
So we are all doing the same home work?
Strange how the most up-voted answer is wrong. Remember, draw/fillOval take height and width as parameters, not the radius. So to correctly draw and center a circle with user-provided x, y, and radius values you would do something like this:
public static void drawCircle(Graphics g, int x, int y, int radius) { int diameter = radius * 2; //shift x and y by the radius of the circle in order to correctly center it g.fillOval(x - radius, y - radius, diameter, diameter); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With