javaswingjlabeljmapviewer

Adding a JLabel to a JMapViewer


Hello I am trying to add a JLabel to a JMapViewer, my current code is

 JLabel label = new JLabel(jlabels[x]);
        Point point = map.getMapPosition(lat, lng, false);
        map.add(label);
        label.setLocation(point);
        MapMarker marker = new MapMarkerDot(lat, lng);
        map.addMapMarker(marker);
        map.validate();
        map.repaint();

However it won't seem to add the label at all. I am no sure what else I could do to make it work. There are a few other questions like this but none have any answers so was wondering if anyone could help?


Solution

  • Note that JMapViewer extends JPanel and invokes setLayout(null). Absent something equivalent to label.setBounds(), the label will never appear. Instead, leverage one of the MapMarkerDot constructors that admits a label string:

    Coordinate paris = new Coordinate(48.8567, 2.3508);
    map.addMapMarker(new MapMarkerDot("Paris", paris));