Search code examples
javaswingjtreeopenstreetmap

swing mappanel map refresh


Currently I am working on a swing application, consisting of a frame with splitpanel. In the left panel I have a jtree, listing all the countries in the world, in the right panel I have an OpenStreetMap, showing a map at startup (which works). The nodes of the jtree are linked to the valueChanged(..) event handler:

/** Required by TreeSelectionListener interface. */
public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

    mapPanel = drawOpenStreetMap(45, 65, 12);
    mapPanel.repaint();
    repaint();
    splitPane.repaint();
    repaint();
    updateUI();
}

MapPanel drawOpenStreetMap(double lon, double lat, int zoom) {
    mapPanel = new MapPanel(); // just a JPanel extension, add to any swing/awt container
    mapPanel.setZoom(zoom); // set some zoom level (1-18 are valid)
    Point position = mapPanel.computePosition(new Point2D.Double(lon, lat));
    mapPanel.setCenterPosition(position); // sets to the computed position
    mapPanel.repaint(); // if already visible trigger a repaint here
    return mapPanel;
}

The valueChanged method gets called on clicking on a jtree node and the drawOpenStreetMap get called indeed and I expected the map to update and show a new location. But nothing changes. The map created at startup remains visible unaltered. The code of the valueChange method shows a number of repaint() calls etc. I have tried, to no avail.

Here is a pointer to the MapPanel source code.

Would be greatful if somebody could tell me how to update the map. Thanks in advance!

Postscript: I refered to the wrong MapPanel; it must be this one.


Solution

  • It seems that you didn't add the MapPanel instance you created to the parent container like SplitPanel in the valueChanged() methods.

    When valueChanged() method invoked, you call drawOpenStreetMap() method to create a MapPanel instance, however, you didn't add it to the SplitPanel. That's why the new location of map didn't appear. Perhaps you need to insert the code like the following:

    public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    
        mapPanel = drawOpenStreetMap(45, 65, 12);
        rightPanel.add(mapPanel); // rightPanel is the panel in the right side of split pane.
        ...