java - JMapViewer, MouseListener called 2 times -
working jmapviewer, strange behavior of component recognized. using defaultmapcontroller map position (lat, lon).
import java.awt.graphics; import java.awt.point; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import javax.swing.jframe; import org.openstreetmap.gui.jmapviewer.defaultmapcontroller; import org.openstreetmap.gui.jmapviewer.jmapviewer; public class test extends jmapviewer{ public test() { addmouselistener(new defaultmapcontroller(this) { public void mouseclicked(mouseevent e){ point start = e.getpoint(); system.out.println(e.getpoint()); } }); } protected void paintcomponent(graphics g){super.paintcomponent(g);} public static void main (string [] args){ jframe jf = new jframe(); jf.setsize(800, 600); test t= new test(); jf.add(t); jf.setvisible(true); } }
running code, after left mouse button pressed, method mouseclicked() gets called multiple times (2x). after replacement
addmouselistener(new defaultmapcontroller(this) {
with
addmouselistener(new mouseadapter() {
the code works correctly, method gets called 1x. problem? bug inside library or syntax wrong or unsafe? how avoid issue? help.
your test
extends jmapviewer
, adding mouselistener
in instance initializer block. consequence, "default constructor call no-argument constructor of superclass." superclass, jmapcontroller
, adds mouselistener
—you guessed it—a second time.
public jmapcontroller(jmapviewer map) { this.map = map; if (this instanceof mouselistener) map.addmouselistener((mouselistener) this); … }
instead, create new jmapcontroller
or defaultmapcontroller
, shown here, , use construct 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); } }
Comments
Post a Comment