I would like to add a mouse listener on my OpenGL graphical objects. What is the best way to do this?
If you use a GLCanvas or a GLJPanel, you can add a mouse listener to this. If you use a GLWindow, use the mouse listener provided in JOGL 2.
Yes, I know I can add a listener to the canvas, but is it possible to add a listener on a primitive? Or do I have to get the position of each primitive and match them against the mouse pointer´s X and Y values?
take a look at the jogl picking demo, redbook should have one too.
Warning: SELECTION mode in OpenGL has the performance characteristics of a turd.
so you may want to use something like this (color coded picking) : http://www.lighthouse3d.com/opengl/picking/index.php3?color1
Alternatively, you may want to do picking by raycasting into the geometry. Personally, I’ve implemented it with colour-coding in my own program, but I also work on another project where it’s done the other way.
I suppose if you raycast, you don’t need to have an active GL context at the time, FWIW.
I haven’t really thought it through, but you might find it useful to design an interface for primitives so that some central bit of your program does the picking (with whatever method you choose), and generates callbacks in the way you originally hoped for - either immediately, or perhaps with SwingUtilities.invokeLater().
This can be seen as a collision testing problem. You are checking for collision between the unprojected line that passes through the pixel in the screen and your camera and all the world geometry that fits inside the visible area. A physics api like Bullet might be able to do this with advanced algorithms that take much less time than checking all the triangles of all objects in your scene.