How can you add several elements to a JScrollPane

java, jscrollpane, swing

Solution

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:

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);

Problem

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!

Original source

Related problems