Skip to main content

[JAVA2D] Drawing arrows from General Path

1 reply [Last post]

I have the following code:

// get angle of line from 0 - 360
theta = Math.atan2(( point1.getY() - point2.getY()),(point1.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);

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


Walter Shirey

To unsubscribe, send email to and include in the body
of the message "signoff JAVA2D-INTEREST". For general help, send email to and include in the body of the message "help".

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

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


public void paintComponent(Graphics g)

Graphics2D g2D = (Graphics2D) g;
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);

Area area = new Area(path);

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.