I'm really stuck on how to go about programming this. How to draw a circle in Java with a radius and points around the edge?
I need to draw a circle within a JFrame with a radius and points around the circumference. i can mathematically calculate how to find the coordinates of the point around the edge but i cant seem to be able to program the circle. I am currently using a Ellipse2D method but that doesn't seem to work and doesn't return a radius, as under my understanding, it doesn't draw the circle from the center rather from a starting coordinate using a height and width.
My current code is on a separate frame but I need to add it to my existing frame.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class circle extends JFrame {
public circle() {
super("circle");
setSize(410, 435);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Panel sp = new Panel();
Container content = getContentPane();
content.add(sp);
setContentPane(content);
setVisible(true);
}
public static void main (String args[]){
circle sign = new circle();
}
}
class Panel extends JPanel {
public void paintComponent(Graphics comp) {
super.paintComponent(comp);
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setColor(Color.red);
Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 350F, 350F);
comp2D.fill(sign1);
}
}
I recommend to take some time to review the "midpoint circle algorithm or Bresenham's circle algorithm". The accepted solution is based on very costly math operations like float multiplication and trigonometric functions.
Try something like this:
You can also override the paint method in the frame class, but then the you would have to calculate in the size of the window decorations and it gets dirty there...
Points on a circle may be specified as a function of the angle θ:
Here, increments of 2π/8 are shown.
Addendum: As suggested in a comment by @Christoffer Hammarström, this revised example reduces the number of magic numbers in the original. The desired number of points becomes a parameter to the constructor. It also adapts the rendering to the container's size.
Use Minueto.