Shannon Shannon - 2 months ago 16
Java Question

Java AWT fillOval() not working

I'm working on a program that draws a graph, so I would like to draw points! I'd like the points to be circular since that's usually how points are represented, and to the best of my knowledge,

g2.fillOval(x, y, height, width)
should draw a filled oval with height
height
and width
width
at
(x, y)
. This is my code at the moment:

private void drawCenteredCircle(Graphics g, int x, int y, int radius) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(pointColor);
g2.fillOval(x-radius, y-radius, 2*radius, 2*radius);
g2.dispose();
}


Which is then called in the
paintComponent()
method of a
JPanel
. It does draw, so I know the code is functioning, but for some reason, it draws a square, like so:
my square oval :(

enter image description here

I also tried this:

private void drawCenteredCircle(Graphics g, int x, int y, int radius) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(pointColor);
g2.fill(new Ellipse2D.Float(x-radius, y-radius, 2*radius, 2*radius);
g2.dispose();
}


But got the same result. Any help as to how to draw a filled circle/ellipse would be much appreciated.

Answer

You will want to set your Graphic2D's RenderingHints to handle aliasing. This smooths out the jaggies that may be causing your (small) circle to render as a square. Something like:

Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);