假设 Map3 是以下类:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JPanel;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.DefaultMapController;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.MapPolygonImpl;
public class Map3 {
private JPanel p;
private JMapViewer map;
private double lat, lon;
public Map3()
{
p = new JPanel();
map = new JMapViewer();
p.setLayout(new BorderLayout());
new DefaultMapController(map) {
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
lat = map.getPosition(p).getLat();
lon = map.getPosition(p).getLon();
}
//Where to locate the method ????
protected void paintComponent(Graphics g){
Coordinate c1= new Coordinate(lat,lon),c2= new Coordinate(lat+10,lon+10); //Draw the line
List<Coordinate> route = new ArrayList<Coordinate>(Arrays.asList(c1, c2, c1));
map.addMapPolygon(new MapPolygonImpl(route));
}
};
p.add(map);
p.setVisible(true);
}
public JPanel getJPanel() {return p;}
}
为了避免鼠标监听器的双重调用,请参阅问题
JMapViewer、MouseListener 调用了 2 次
该类不是直接从 JMapViewer 派生的。使用鼠标单击我得到了两个坐标 [lat, lon],它们将用于绘制由 P1、P2 给出的线,其中 P1=[lat, lon], P2=[lat+10, lon+10]。
我不确定应该将方法paintComponent() 放置在何处以便能够将一些绘图添加到OSM 地图。
public class TEST
{
public static void main (String [] args)
{
JFrame jf = new JFrame();
jf.setSize(800, 600);
Map3 p = new Map3();
jf.add(p.getJPanel());
jf.setVisible(true);
}
}
当前版本不好用,paintComponent() 没有被调用...
谢谢你的帮助。