【问题标题】:Add mouse event to JMapViewer mapMarker将鼠标事件添加到 JMapViewer mapMarker
【发布时间】:2015-08-17 15:01:16
【问题描述】:

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

【问题讨论】:

  • 考虑在这个问题中添加 Swing 标签。

标签: java swing awt jmapviewer


【解决方案1】:

您从TrashGod's MouseListener solution 开始是正确的,但您需要添加更多代码,关键部分是,您需要获取用户按下的点位置,即@987654324 @ 方法会告诉你,然后根据该信息,以及组件的“活动”区域的边界来决定是否响应。比如:

@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 循环中的包含情况。

【讨论】:

  • 正确;使用Shape#contains() 的命中测试方案被引用here
  • 我认为它不使用形状派生对象。 MapMarkerCircle 是一个扩展 MapObjImpl 抽象类的类。它有一个paint(Graphics g, Point position, int radio) 方法。 svn.openstreetmap.org/applications/viewer/jmapviewer/src/org/…
  • @s_puria: 如果有位置,那么您可以创建自己的代码测试来查看点击是否在这些对象之一上或附近,我建议您尝试这样做。跨度>
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 2014-11-14
    • 2011-05-29
    • 2014-07-29
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多