I am working on an application that involves the user requiring to hover over several moving dots on the screen in order to launch specific popups. At the moment, i am listening for mouseMoved
events on the JPanel
onto which the dots are rendered, and then launching the required pop ups whenever the cursor is within a specific distance of a dot.
When i have hundreds of dots - this probably becomes quite expensive.
Wouldnt the ideal solution be to represent my 'dots' as small components and register a mouse listener with each dot?
Does anyone know how i might represent a small ellipse with a JComponent
?
Many thanks
You write "this probably becomes quite expensive"
Whether you code the "isMouseCloseToDot" method yourself, or whether you use something built into Swing, in either case the work still needs to be performed by the computer to find out whether a dot is activated.
I recommend sticking with your current approach unless you have determined that this approach is indeed too expensive. Do a small test with a couple of hundred dots. Is the response time acceptable?
Here is some old code which shows how to create a "round" JButton. I would extend JComponent instead and the important methods to override are paintComponent() and contains():
This simplifies the hit detection easily since there is no custom code. Also it allows you to control overlapping of compnents easily since you can control the Z-Order of each component.
Not sure which approach is more expensive, but component based approach is definitely easier to implement.
All you have to do is to create your own component, override
paint
andcontains
methods. Add it to the specific position in the container (using absolute layout or any other depending on your needs). Your listeners will become part of your new component providing components behavior.From the design and program organization point of view this is much more superior approach.