Ojouk Ojouk - 1 year ago 161
Java Question

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 is what I currently have:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RandomCircle extends JFrame {
private DrawPanel dpCircle;
private JTextArea display;
private JButton btnGenerateRandomCircle;

public RandomCircle() {
super("Random Circle");
dpCircle = new DrawPanel();
JButton btnGenerateRandomCircle = new JButton("Click for next random circle");

display = new JTextArea(5, 30);

btnGenerateRandomCircle.addActionListener(new MyButtonListener());
add(btnGenerateRandomCircle, BorderLayout.NORTH);
add(dpCircle, BorderLayout.CENTER);
add(display, BorderLayout.SOUTH);
setSize(400, 400);

private class MyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() != btnGenerateRandomCircle) {
dpCircle.setRadius((int) (1 + Math.random() * 100));
display.setText(String.format("Area: %.2f"
+ "\nRadius: %d"
+ "\nDiamter: %d"
+ "\nCircumference: %.2f",
dpCircle.getArea(), dpCircle.getRadius(),
dpCircle.getDiameter(), dpCircle.getCircumference()));

private class DrawPanel extends JPanel {
// fields
private int radius;

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

// method to receive radius
public void setRadius(int radius) {
this.radius = (int) (1 + Math.random() * 100);


public int getDiameter() {
return (2 * radius);

public double getCircumference() {
return (2 * Math.PI * radius);

public double getArea() {
return (radius * radius * Math.PI);

public int getRadius() {
return radius;

public static void main(String args[]) {
new RandomCircle();

Answer Source

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:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download