I am working on a program in which I want to draw a line from circle's center to its parametric point. But it draws line out of circumference and inside circumference. I want to draw line exactly on circumference according to X
and Y
angles.
Circle center points:
x = 200
y = 100
radius= 100
public SecondActivity(String azim,String ele) {
initialize();
setTitle("My WIndow");`
angle_x = Integer.parseInt(azim);
angle_y = Integer.parseInt(ele);
x = 200+r*Math.cos(angle_x);
y = 100+r*Math.sin(angle_y);
}
public void paint(Graphics g) {
super.paint(g);
drawCircle(g,200,100,r);
drawLine(g);
}
public void drawCircle(Graphics g,int x,int y,int r) {
g.setColor(Color.BLACK);
g.drawOval(x, y, r*2,r*2);
}
public void drawLine(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.draw(new Line2D.Double(300.0d,200.0d,x,y));
}
You have a couple of errors in your code (and logic):
You're using 2 angles to calculate the
X
andY
coords, thus, giving you weird results. As per this Wikipedia image the angle theta is the same for bot coords.You're using the angle in degrees, but
Math.cos(angle)
andMath.sin(angle)
require that theangle
is given in radians, so, you must convert the angles to radians as likeMath.roRadians(angle)
, as shown in this question: How to use Math.cos() & Math.sin()?Not really an error but a suggestion from @MadProgrammer in this other answer of mine to use the Shape API instead of pure
.drawOval
as you did while drawing the line, changedrawOval
todraw(new Ellipse2D.Double(...))
.You're overriding
paint(Graphics g)
method instead ofpaintComponent(Graphics g)
this could cause some issues while painting. UseJPanels
and override theirpaintComponent
method and add thoseJPanel
s to yourJFrame
.Having said all of the above, I came to a good example that follows the above advises as well as solving the issue:
Here are some screenshots of the output at 0, 60 and 90 degrees.