views:

77

answers:

2
+3  Q: 

Picking in java 2d

I am using java2d to draw a simple graph at the moment I have implemented picking by calling contains(MousePoint) for each object/shape, this works but scales linearly.

Is there a more efficient method for picking in java2d?

+4  A: 

Yes, although the full answer would be too long for this space.

First of all, unless you have a lot of nodes, then linear will most likely be fine, and you shouldn't change anything unless performance is already seen to suffer.

Second, what you want, in general, is to apply some sort of hierarchical decomposition, such as a quadtree. This is a way of using more memory (and more time up front, amortized during searches) to eliminate items from consideration in a so-called "broad phase". Some diligence on the web will help, as will the book "Real-Time Collision Detection", by Christer Ericson.

Jonathan Feinberg
Thats the direction I was thinking but that requires me to implement it myself. Maybe it is better to use java3d and use the scenegraph and picking already implemented.
stimpie
+1 for "optimize when you need to".
Alex Feinman
+1  A: 

As long as your only selecting areal shapes (rectangles, circles), it should work with the contains() method. There's just one pitfall just in case you have overlapping shapes and you point to a place where shapes actually overlap. But that's a question of requirement whether you want to select all shapes, the one on top or the first shape you find in your collection.

The contains() method will not work in case you want to select Line2D type shapes. They don't have an area so the contains() method always return false. But there's already a solution on SO for this problem.

Andreas_D