Working with JMapViewer, a strange behavior of the component was recognized. I am using DefaultMapController to get the map position (lat, lon).
import java
Your Test
extends JMapViewer
, adding a MouseListener
in an instance initializer block. As a consequence, the "default constructor will call the no-argument constructor of the superclass." The superclass, JMapController
, adds your MouseListener
—you guessed it—a second time.
public JMapController(JMapViewer map) {
this.map = map;
if (this instanceof MouseListener)
map.addMouseListener((MouseListener) this);
…
}
Instead, create a new JMapController
or DefaultMapController
, as shown here, and use it to construct your JMapViewer
.
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import org.openstreetmap.gui.jmapviewer.DefaultMapController;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
/**
* @see https://stackoverflow.com/a/39461854/230513
*/
public class TestMapController {
private void display() {
JFrame f = new JFrame("TestMapController");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMapViewer map = new JMapViewer();
new DefaultMapController(map) {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
};
f.add(map);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new TestMapController()::display);
}
}