简体   繁体   中英

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 :(

在此处输入图片说明

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM