I’m working on a telecommunication application to visualize signal strengths using java draw circle
. I have the X and Y coordinates of a mobile signal transmitter and a calculated radius.
However, when using g.drawOval(X, Y, r, r)
, the X and Y coordinates are treated as the top-left corner instead of the center.
How can I correctly position the circle?
By default, g.drawOval(x, y, width, height) treats (x, y) as the top-left corner. To make (X, Y) the center, subtract half the radius from both coordinates:
i
mport javax.swing.*;
import java.awt.*;
public class CircleDrawer extends JPanel {
private int centerX = 200;
private int centerY = 200;
private int radius = 100;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
CircleDrawer panel = new CircleDrawer();
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
-
centerX - radius, centerY - radius shifts the top-left corner so the circle is centered.
-
radius * 2 ensures the circle has the correct diameter.
For anti-aliased circles (smoother edges), use Graphics2D:
import javax.swing.*;
import java.awt.*;
public class SmoothCircleDrawer extends JPanel {
private int centerX = 200;
private int centerY = 200;
private int radius = 100;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
g2d.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
SmoothCircleDrawer panel = new SmoothCircleDrawer();
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
- Graphics2D improves rendering quality using anti-aliasing.
- Ideal for high-resolution or scientific visualizations.
If you want a solid-filled circle, use fillOval():
g.setColor(Color.GREEN);
g.fillOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
This will draw a filled circle instead of just an outline.