5

So I am trying to add more than one element to a JScrollPane element but so far I haven't been able to pull it of. I can make it so that the first element shows up ,which in my case is a picture. But after adding in an extra panel to the JScrollPane ,the first element disappears and even the second element ,the new panel , doesnt show on my JScrollPane.

        JFrame scherm = new JFrame("t?");
    scherm.setVisible(true);
    scherm.setSize(300, 300);
    scherm.setLocationRelativeTo(null);
    scherm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //
    String path = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking\\map\\provinces.bmp";
    Image image = ImageIO.read(new File(path));
    ImageIcon icon = new ImageIcon(image);


    JLabel label = new JLabel(icon);
    JScrollPane scroll = new JScrollPane(label);
    JPanel paneel2= new JPanel();
    paneel2.setSize(new Dimension(400,400));
    scroll.getViewport().add(paneel2,null);

    scherm.add(scroll);

Thank you for your time!

dic19
  • 17,821
  • 6
  • 40
  • 69
BURNS
  • 711
  • 1
  • 9
  • 20
  • 2
    More of a work around than an answer... but typically in these situations I build a JPanel which contains all of the elements I wish to enclose inside of a JScrollPane, then I add that single JPanel to the JScrollPane. – Mark W Feb 14 '14 at 20:48
  • Sounds reasonable and would probably work better than what I have. But im a stubborn basterd and love to see a solution to my exact problem. :) – BURNS Feb 14 '14 at 20:52
  • 1
    @BURNS Mark's solution is the solution to your exact problem ;) – Laf Feb 14 '14 at 21:04
  • So you can only add one element to a JScroll ? – BURNS Feb 14 '14 at 21:09
  • 1
    This [question](http://stackoverflow.com/q/14149608/994125) has interesting details for your case, even though this isn't a duplicate. – Laf Feb 14 '14 at 21:14
  • 1
    `JViewport` is a special container that can contain only one child, which can only be set via the `setView` method. All the other `add` methods have being overridden to perform NOOP. You simply can not add multiple components to a `JViewport` – MadProgrammer Feb 14 '14 at 22:28

1 Answers1

12

By doing this:

scroll.getViewport().add(paneel2,null);

You're trying to add a component to the scroll pane's JViewPort shown in the picture below:

enter image description here

This makes no sense. As stated in How to Use Scroll Panes trial:

A JScrollPane provides a scrollable view of a component.

This single component is the view port's view. So if you want to have more than a single component in your scroll pane you must to wrap all those components in a lightweight component such as JPanel and set this one as the scroll pane's view port view:

JPanel content = new JPanel();
content.add(label);
content.add(paneel2);

scroll.setViewportView(content);
dic19
  • 17,821
  • 6
  • 40
  • 69