0

如何将 mouseListener 添加到使其像按钮的 MapMarker(MepMarkerDot 或 MapMarkerCircle)?我尝试了这个解决方案,但它使整个地图可点击(鼠标事件适用于所有地图)。

4

2 回答 2

1

从TrashGod 的 MouseListener 解决方案开始,您走在正确的道路上,但您需要添加更多代码,关键部分是,您需要获取用户按下的点位置,该MouseEvent#getPoint()方法会告诉您,然后根据该信息,组件的“活动”区域的边界决定是否响应。就像是:

@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.
}

请注意,如果您的代码使用 Shape 派生对象,例如 Ellipse2D 或 Rectangle2D,您可以使用它们的contains(Point p)方法轻松告诉您点按是否在 Shape 内。或者,如果您要检查多个位置,您可能有一个 Shapes 集合,在 mousePressed 或(如果有)isPointValid 方法中遍历它们,并检查 for 循环中的包含情况。

于 2015-08-17T15:21:11.820 回答
0

我发现了这个很好的例子:

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

它有一个接口 MarkerClickable 和它自己的实现 MapMarker 和 MarkerClickable 的 LabeledMarker:

    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; 
} 
于 2017-10-26T22:12:47.530 回答