Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a line connecting two rectangles

I am making my own class diagram app in Swing/AWT but i stopped at this functionality:

  • I want to draw a line between the Class rectangle that already selected and to the target Class rectangle, but line has a feature which is whenever i move one of the rectangles the line that join them get bend in a straight fashion following the moving rectangle , i hope the following picture demonstrate what i want to achieve: alt text

A general guideline or a sample code is highly appreciated

like image 509
skystar7 Avatar asked Dec 01 '25 08:12

skystar7


2 Answers

I don't know Java, but the steps you could follow are these:

  • Find the middle of each line of the rectangles (should be easy, just avarage x1+x2 and y1+y2)
  • Determine the edges that are closest to each other using Pythagoras formula on the points you got in the previous step.
  • Start drawing a line starting at xa,ya (first point you got in the step above), and draw it in the direction away from the rectangle. You should know this direction, because you can know the line segment this point is on.
  • Do the same for xb,yb (point on the second rectangle). If the lines are in opposite directions, you should draw them to halfway xa-xb or ya-yb (depending on if you're drawing horizontally or vertically). If they are perpendicular (is that the right word?) you should draw them to the point where they cross, so you draw the line from xa,ya to xa,yb or xa,ya to xb, ya, depending if you draw the horizontal or vertical line.
  • There should be some additional check to see if the rectangles overlap. You should not draw lines in the same direction for example. Maybe it would suffice for you to draw just a diagonal line between the two points in those cases where you cannot determine how to draw these straight lines.

For the implementation you could build a line class that uses the observer pattern to listen to the two rectangles it follows, so it can update itself whenever one of them moves or resizes.

like image 69
GolezTrol Avatar answered Dec 03 '25 21:12

GolezTrol


http://java-sl.com/connector.html Hope this helps.

like image 32
StanislavL Avatar answered Dec 03 '25 22:12

StanislavL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!