# [JAVA2D] Drawing arrows from General Path

I have the following code:

// get angle of line from 0 - 360

theta = Math.atan2(( point1.getY() - point2.getY()),(point1.getX() -

point2.getX()));

theta = 180 - Math.toDegrees(theta);

GeneralPath arrowhead = new GeneralPath();

double distance = point1.distance(point2);

// create arrowed line general path

arrowhead.moveTo( 0 , 0);

arrowhead.lineTo( (float) distance, 0 );

arrowhead.lineTo( (float) (distance - 8), (float) 6);

arrowhead.lineTo( (float) (distance - 8) , (float) -6);

arrowhead.lineTo( (float) distance , (float) 0 );

AffineTransform at = new AffineTransform();

at.rotate(theta, 0 ,0 );

at.translate(point1.getX() , point1.getY() );

Shape arrow = at.createTransformedShape(arrowhead);

System.out.println(arrow);

g2.draw(arrow);

The desired effect is to have an arrowed line drawn from point1 to

point2. So I thought to just draw an abstract line from the point (0,0)

with a length of distance, and to just rotate and translate this shape

to be at point 1. However, I'm not getting the results I'm looking for.

Anyone might know what the problem is? I think it has to do with the

transform. Is that the correct way to set up a translate and rotate

transform?

Thanks,

Walter Shirey

===========================================================================

To unsubscribe, send email to listserv@java.sun.com and include in the body

of the message "signoff JAVA2D-INTEREST". For general help, send email to

listserv@java.sun.com and include in the body of the message "help".

[att1.html]

I have drawn a line with arrow but it is has some problem.It works OK. Now I draw a line with arrow on the panel.

class ArrowLinePanel extends JPanel

{

Line2D line = new Line2D.Float(100f, 100f, 300f, 300f); // confirm the line position

ArrowLinePanel()

{

setBackground(Color.white);

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

Graphics2D g2D = (Graphics2D) g;

g2D.setColor(Color.red);

g2D.draw(line); // draw line without arrow.

double x1 = line.getX1();

double x2 = line.getX2();

double y1 = line.getY1();

double y2 = line.getY2();

double length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); // compute the line's length

g2D.translate(x1, y1);

double roate = Math.atan((y2-y1)/(x2-x1)); // compute the angle between line and X axis.

// draw arrow

GeneralPath path = new GeneralPath();

path.moveTo((float)length, 0);

path.lineTo((float)length - 10, -5);

path.lineTo((float)length - 7, 0);

path.lineTo((float)length - 10, 5);

path.lineTo((float)length, 0);

path.closePath();

Area area = new Area(path);

g2D.fill(area);

}

}

Some problem is:

If the angle between the line and X axis is 90, the length of line will be recompute. This is a small program, you can improve on it.