JMapViewer, MouseListener called 2 times

后端 未结 1 2002
南方客
南方客 2021-01-15 11:48

Working with JMapViewer, a strange behavior of the component was recognized. I am using DefaultMapController to get the map position (lat, lon).

import java         


        
相关标签:
1条回答
  • 2021-01-15 12:47

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题