Search code examples
javajpaneljscrollpaneimageiconscrollpane

Using JScrollPane on JLabel in Java


Somehow I don't the scrollpane to show up. What do I need to change?

bigP = new JLabel();
setLayout(new BorderLayout());

JPanel helper = new JPanel(new FlowLayout());
helper.add(bigP);
helper.setPreferredSize(new Dimension(500,600));
helper.add(new JScrollPane(bigP, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));

picPane = new JPanel(new BorderLayout());
picPane.add(helper,BorderLayout.CENTER);
picPane.setMaximumSize(new Dimension(500, 600));
picPane.setVisible(true);

add(picPane, BorderLayout.CENTER);

After an image is chosen this line is called:

bigP.setIcon(img);

I figured out that I most certainly will need the helper-panel as the BorderLayout would only take one component (as far as I understood). Unfortunately my scrollpane won't show up at all though the picture does.


Solution

  • helper.setPreferredSize(new Dimension(500,600));
    

    Don't hardcode a preferred size. The panel will determine its own preferred size based on the components added to the panel.

    JPanel helper = new JPanel(new FlowLayout());
    helper.add(bigP);
    sc = new JScrollPane(bigP,JScrollPane
    

    Also a component can only have a single parent. In the above code you attempt to add "bigP" to "helper". But then in the next statement you add it to the scrollpane, so "bigP" is removed from the "helper" panel and will only appear in the scrollpane.

    //pic.add(bigP,BorderLayout.CENTER);
    pic.add(helper,BorderLayout.CENTER);
    

    Also you never add the scroll pane to the "pic" panel. The code should be:

    //pic.add(bigP,BorderLayout.CENTER);
    //pic.add(helper,BorderLayout.CENTER);
    pic.add(sc, BorderLayout.CENTER);
    

    So now you should have a structure that looks like:

    - pic
        - sc
            - bigP
    

    It would also help if you use more descriptive names so everybody knows what those variable are.