skystar7
skystar7

Reputation: 4597

Drawing a line connecting two rectangles

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

A general guideline or a sample code is highly appreciated

Upvotes: 3

Views: 5544

Answers (4)

StanislavL
StanislavL

Reputation: 57421

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

Upvotes: 4

GolezTrol
GolezTrol

Reputation: 116200

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.

Upvotes: 5

davogotland
davogotland

Reputation: 2777

try creating a class named "ConnectingLine" or similar. this class will then have several segments (that's the name of these line parts in dia, which is currently my favorite uml modeling tool) which will be calculated one by one. you'll have a sepaparate class for this of course ;) called maybe "LineSegment". i think this should make it easier for you to perform the mathematical calculations required to perform this task.

this could also enable making segments "auto routed or not" easy d(^_^)b

Upvotes: -1

Klark
Klark

Reputation: 8300

Try with observer pattern. All lines that are connected with a moving object should be notified with new position of the object and 'bent' properly. Of course, first implement some logic that will connect 2 objects.

Upvotes: 1

Related Questions