problem with ellipse drawing at the line end
Hi
I want to draw a ellipse at the end of a line shape(line and ellipse repaints on mouse move)
I am getting line's endPoint by using getP2() method and then setting
ellipse's frame to that point's x and y and some width and height.
But the problem is that ellipse doesn't get drawn at that exact point(line end point).
It's off by 10 to 12 pixels .
What could be the problem?
# 1
If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE[/url]) that demonstrates the problem.
And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting[/url] when posting code.
# 2
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EllipseDraw
extends JPanel
{
Line2D line = new Line2D.Double(new Point2D.Double(20, 20), new Point2D.Double(70, 30));
public static void main(String[] args)
{
EllipseDraw ellipseDraw = new EllipseDraw();
ellipseDraw.setBorder(BorderFactory.createRaisedBevelBorder());
JFrame frame = new JFrame();
frame.getContentPane().add(ellipseDraw);
frame.setSize(200, 200);
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
Ellipse2D ellipse = new Ellipse2D.Double(line.getP2().getX(), line.getP2().getY(), 20, 20);
g2d.setStroke(new BasicStroke(2));
g2d.setPaint(Color.magenta);
g2d.draw(line);
g2d.draw(ellipse);
}
}
# 3
If you read the API of Ellipse2D.Double you will see that the first 2 parameters are the x,y locations of the bounding box of the Ellipse.
And this explains the offset between the line and the ellipse itself.
Calculating where to place the ellipse so the line touches the ellipse is a bit more complicated.
In your example the location is this:
Ellipse2D ellipse = new Ellipse2D.Double(line.getP2().getX()-0.2, line.getP2().getY()-8.04, 20, 20);
You need to calculate the intersection between the line and the ellipse when the center of the ellipse is placed in the second point, and then move the ellipse by the different between the intersection point and the center of the ellipse.