1

I want to set up a grid of circles (non-overlapping) so that, when the mouse pointer is over one of them, that circle changes colour. I have experimented and so far have two options:

  1. Use a container e.g. JPanel. Use MouseMotionListener.mouseMoved(MouseEvent e) to get the x and y coordinates of the mouse pointer at all times. Then, if the coordinates lie within one of the circles, use repaint() to repaint the whole container.

  2. Set each circle as a container. Use MouseListener.mouseEntered(MouseEvent e) to detect when the mouse pointer moves over a circle. Then redraw that container only.

Is #2 the best approach? If so, how can I set up a circular container? Is there a better approach than either of the above?

danger mouse
  • 1,457
  • 1
  • 18
  • 31
  • 1
    It is possible to make non rectangular components by overriding [contains(int, int)](https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#contains%28int,%20int%29). Whether that's better alternative depends on your needs (You don't need to repaint the entire panel in the first case either - just use a `repaint()` variant that specifies the bounds, and make the panel smart enough to optimize partial draws). – kiheru Nov 06 '15 at 19:21
  • 1
    @mlm Personally I would go with the first approach. I just thought abit further. Imagine having a grid of 1000x1000. That would be 1 million components. And if you just want to change their color and nothing else, I don't see the need to have so many objects. (In 2nd approach) it seems like you plan to have so many objects, just to make use of their mouse-entered behaviour (other than that, u don't need them to be a component). While with first approach, you don't need to maintain so many object (circles), basically just repaint the area you need to repaint. (which is exactly what you want). – user3437460 Nov 06 '15 at 19:29
  • It may help to [profile](http://stackoverflow.com/q/2064427/230513) both approaches. – trashgod Nov 06 '15 at 19:41
  • Thanks kiheru and user 3437460 - that's all very helpful. – danger mouse Nov 06 '15 at 19:54
  • It's a little involved (as it's solving another issue), but something like [this](http://stackoverflow.com/questions/30471010/placing-correct-discs-connect-four-java-game-with-drawing-panel/30472078#30472078) or [this](http://stackoverflow.com/questions/14617849/graphics2d-circular-table/14618776#14618776) might give you some ideas – MadProgrammer Nov 06 '15 at 21:58

1 Answers1

2

If so, how can I set up a circular container?

Check out Playing With Shapes.

You can use the ShapeComponent to create a circles that act just like components. So you can build your grid just like you would with any other Swing component.

camickr
  • 321,443
  • 19
  • 166
  • 288