Ojouk
Ojouk

Reputation: 25

How to draw a random circle in center using the center as reference with Graphics#fillOval

Currently when a button is clicked, the circle will draw at g.fillOval(getWidth()/2 - 50, getHeight()/2 - 50, radius, radius);

Here I have:

  private class DrawPanel extends JPanel {
    private int radius;

    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.fillOval(getWidth()/2 - 50, getHeight()/2 - 50, radius, radius);
    }

Upvotes: 0

Views: 1153

Answers (1)

Lory A
Lory A

Reputation: 530

Your question is not very clear, and you posted a bit too much code so let me generalize.

When you draw a circle with Graphics#fillOval , the point of reference if the upper left corner of the square that the Oval is inscribed into.

So if you want to use the center as reference, given a radius r you should draw in:

(xCenter - r, yCenter - r, r*2, r*2)

Also since it's a circle, consider using Graphics2D with Antialising on. Here the docs to do that:

https://docs.oracle.com/javase/tutorial/2d/advanced/quality.html

Upvotes: 2

Related Questions