Search code examples
javaswingjpaneljscrollpane

JPanel in JScrollPane not showing


I'm busy making a level designer for a game I'm planning to make in Java. I have a panel for settings, for example the size of the level or what the background will be. You can also select images to put on the other panel, the 'DesignerPanel' and then you should be able to click on that panel to put it in a specific place. I put the DesignerPanel in a JScrollPane to scroll around bigger levels.

The problem is that the JScrollPane doesn't appear and neither does the panel that should be in it. I have found some questions about the scroll bars not appearing, but in my case nothing appears. Well, at least, almost nothing.

You can see really small stripes of the DesignerPanel to the right and below. However, there is no trace of the JScrollPane or the rest of the panel. Resizing or minimizing and unminimizing the screen doesn't make a difference. I would post an image and I think it would surely help, but apparently I need reputation to do that, so sorry about that.

Here's the relevant code I have so far. I have hidden most of the code because it is not important for this error.

package games;

import java.awt.*;
import java.io.*;
import javax.swing.*;

class LevelDesignerScreen extends JFrame
{
    private SettingsPanel sp;
    private DesignerPanel dp;
    private JScrollPane scroller = new JScrollPane();

    LevelDesignerScreen()
    {
        sp = new SettingsPanel(this);
        add(sp, BorderLayout.WEST);
        dp = new DesignerPanel(sp);
        dp.setSize(1000, 1000);
        scroller.setPreferredSize(new Dimension(600, 600));
        scroller.add(dp);
        add(scroller, BorderLayout.CENTER);
    }

    public static void main(String[] args)
    {
        new LevelDesignerScreen();
    }
}

Solution

  • You should use

    scroller = new JScrollPane(dp);
    

    or

    scroller.setViewportView(dp);
    

    instead of scroller.add(dp).

    And on a more general note: if you are having problems with layout, put prime colored line borders on all involved components to see what takes up space and what doesn't.