How can I add mouseListener to a MapMarker (MepMarkerDot or MapMarkerCircle) that makes it like button? I tried this soloution but it makes whole map clickable (mouse Event works on all the map).
Add mouse event to JMapViewer mapMarker
520 views Asked by s_puria At
2
There are 2 answers
0
On
I found this nice example:
It has an interface MarkerClickable and its own LabeledMarker which implements MapMarker and MarkerClickable:
public boolean onClick(final Coordinate p, final MouseEvent e) {
for (final MapMarker x : getMap().getMapMarkerList()) {
if (x instanceof MarkerClickable) {
final MarkerClickable mc = (MarkerClickable)x;
final Rectangle a = mc.getClickableArea();
if (a == null)
continue;
if (a.contains(e.getPoint())) {
mc.onClicked(e.getPoint(), e.getButton());
return false;
}
}
}
return true;
}
You're on the right path to start with TrashGod's MouseListener solution, but you need to add a little more code, the key part being, that you need to get the Point location of where the user pressed, something the
MouseEvent#getPoint()
method will tell you, and then based on that information, and the bounds of the "active" area of the component decide whether to respond. Something like:Note that if your code uses Shape derived objects, such as Ellipse2D or Rectangle2D, you can use their
contains(Point p)
method to easily tell you if the point press was within the Shape or not. Or if there are several locations that you want to check, you may have a collection of Shapes, iterate through them within your mousePressed or (if you have it) isPointValid method, and check containment within the for loop.