Search code examples
javaswinglayoutjscrollpanejlabel

JLabel disappears after scrolling


I've got scroll panel which contains ImageIcon. I want to add JLabel with absolute position in px. What I've got:Swing app image

The code:

public class HelloWorld {


    HelloWorld() {

        JFrame jfrm = new JFrame("Hello, World!");
        jfrm.setSize(640, 480);
        JPanel mapPanel = new JPanel();
        mapPanel.setLayout(null);
        mapPanel.setSize(600,400);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ImageIcon imageIcon = new ImageIcon("src\\SwingExp\\img\\map.gif");
        JScrollPane scrollPane = new JScrollPane(new JLabel(imageIcon));
        scrollPane.setBounds(5,5,600,400);
        JLabel usaLabel = new JLabel("U.S.A.");
        usaLabel.setBounds(210,200,50,25);
        mapPanel.add(usaLabel);
        mapPanel.add(scrollPane);

        jfrm.add(mapPanel);
        jfrm.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new HelloWorld();
            }
        });
    }
}

But if I'll scroll a little, USA label will disappear from map: Swing app image

JLabel positions must be absolute, as you see. How to avoid this?


Solution

  • Add the usaLabel to the label containing the icon, not the scrollpane:

    ImageIcon imageIcon = new ImageIcon("src\\SwingExp\\img\\map.gif");
    JLabel map = new JLabel( imageIcon );
    JScrollPane scrollPane = new JScrollPane( map );
    //JScrollPane scrollPane = new JScrollPane(new JLabel(imageIcon));
    scrollPane.setBounds(5,5,600,400);
    JLabel usaLabel = new JLabel("U.S.A.");
    usaLabel.setBounds(210,200,50,25);
    map.add( usaLabel );
    //mapPanel.add(usaLabel);
    

    Also stop using a null layout everywhere. There is no need for your mapPanel variable. Just add the scrollpane directly to the content pane of the frame. By default the scrollpane will be added to the CENTER and will take up all the space available in the frame.