Add mouse event to JMapViewer mapMarker

520 views Asked by At

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).

2

There are 2 answers

3
Hovercraft Full Of Eels On

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:

@Override
public void mousePressed(MouseEvent e) {
    Point p = e.getPoint(); // this is where the user pressed
    if (isPointValid(p)) {
        // do something
    }
    System.out.println(map.getPosition(e.getPoint()));
}

private boolean isPointValid(Point p) {
    // here you have code to decide if the point was pressed in the area of interest.
}

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.

0
Steve On

I found this nice example:

https://www.programcreek.com/java-api-examples/index.php?source_dir=netention-old1-master/swing/automenta/netention/swing/map/Map2DPanel.java

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; 
}