Search code examples
javaswinglineoverlapjcomponent

Determine component overlapped by Line2D


There are no. of components around and on Line2D.I want to find only the overlapped ones.I tried line.getbounds().intersects(component) but it gives the rectangular area components which I don't need.Also,distance sometimes gives me a component which is very near to Line but not on line.Any solution?


Solution

  • Short answer: check if at least one of these two conditions is true

    • any endpoint of the line is inside the component, use the method contains
    • the line intersects any side of the component bounds, use the intersect method.

    Detailed description: These are the possible cases:

    • one endpoint of the line is inside the component (this include the case where the line is entirely inside the component);
    • the line cross the component but all the end points of the line are outside of the objects;In this case it will intersect two sides, but one is enough to validate.
    • in all other case, the line and the component do not overlap each other and we do not care.

    Only the middle bullet is a bit tricky, however since you are testing only jcomponent, the life is simple, because they are rectangles aligned with the axis. You can easily compute the endpoint of the sides of the bounds of the component. The bounds are given by a point (x,y) the width w and the height h. This gives you the four sides as:

    • (x,y) - (x+w,y)
    • (x,y) - (x, y+h)
    • (x,y+h) - (x, y+h)
    • (x+w,y) - (x+w,y+h)