-
Snapping algorithm
ok heres what i am trying to do.
i have a Jpanel is which i load an image. then the user presses 'generate' button to generate several instances of transparent JPanels with a white border. the user can drag these panels to position them over the image.
What i want to do is make a snap mode in which when activated will automatically snap these transparent panels to each others edges.
off the top of my head one idea that came was to x and y coordinate of all the 4 edges of each panel in an some sort of data structure and whenever the user drags a panel , constantly keep checking its x,y with the stored values and snap when required. however this seems like a not so elegant approach and with a lot of panels would be cumbersome.
Just wondering if anyone has any ideas/suggestions that could do it in a better way.
thanks
ankit
-
-
you could probably set it up so when the item being dragged is released it would only check then and move it to the closest edges. I'm not familiar with JPanel so I can't give too solid an example.
-
What i want to do is make a snap mode in which when activated will automatically snap these transparent panels to each others edges.
There are always a lot of options in building something like this. Are these panels to be in a straight line or a rectangluar shape when snapped?
one idea that came was to x and y coordinate of all the 4 edges of each panel in an some sort of data structure and whenever the user drags a panel , constantly keep checking its x,y with the stored values and snap when required. however this seems like a not so elegant approach and with a lot of panels would be cumbersome.
Agreed. The components will keep the coordinates for you: you can call getBounds on each one and get the origin with the x, y fields. You can get the ne corner x value with either getMaxX or r.x + r.width (x and width fields of Rectangle).
The fun part is to design for fluid resizing. At the snap you could compute the size and location of the desired layout (line, rectangle of rows/columns or other layout) of the panels and adjust their locations relative to this rectangle with either the setBounds or the setLocation method called on each panel.