JScrollPane not reacting due to JPanel not resizing

1k views Asked by At

I have a cardlayout JPanel, inside of which is a JScrollPane, inside of which is a springlayout JPanel. The springlayout JPanel is being dynamically added with JPanels from top to bottom, but when the JButtons go beyond the JPanel, the JScrollPane does not accommodate for the extra content. Also, apparently the springlayout JPanel's height remains 0 despite the content added. Setting the resizable property true does nothing too.

Here is a code fragment. I omitted the cardlayout JPanel and code switching the card.

    SpringLayout mainlayout = new SpringLayout();
    JPanel maincard = new JPanel(mainlayout); // springlayout JPanel
    for (int i = 0; i < info.size(); i++) {
        GridLayout entryLayout = new GridLayout(1, 1);
        JPanel entry = new JPanel(entryLayout);
        entry.setSize(800, 30);

        JButton name = new JButton();
        name.setSize(250, 30);
        name.setText(info.get(i).name);

        entry.add(name);

        mainlayout.putConstraint(SpringLayout.NORTH, entry,
                 i * 100 + 5,
                 SpringLayout.NORTH, maincard); // moves JPanel lower and lower
        maincard.add(entry);
    }
    maincard.setSize(width, 30 * (info.size() + 1));
    maincard.revalidate();
    JScrollPane scroll = new JScrollPane(maincard);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setSize(200, 200); // this and setPreferredSize don't affect
    cardpanel.add(scroll, cardName);
    cardpanel.setSize(20, 200); // no effect
1

There are 1 answers

2
Lasse Jacobs On BEST ANSWER

I have had some problems with this myself. What worked for me was using a borderlayout. And you need to call revalidate after adding a new element in order to update the scrollpanel.

Here is a example of code which I used in my project a while back:

public BookingTable()
{
    super(new BorderLayout());
    _contentPanel = new JPanel();
    _contentPanel.setLayout(new BoxLayout(_contentPanel, BoxLayout.Y_AXIS));
    _scrollPane = new JScrollPane(_contentPanel);

    add(_scrollPane, BorderLayout.CENTER);
}

private void addToPanel(EntryView panel)
{
    panel.setPreferredSize(new Dimension(150, 35));
    panel.setMaximumSize(new Dimension(160, 45));
    panel.setMinimumSize((new Dimension(80, 30)));   

    _contentPanel.add(panel);
    _contentPanel.revalidate();
}

Hope this helps you out! Another tip is that in case you remove elements from the Scrollpane you need to call Repaint in order to actually remove the elements from the UI if you don't they will remain visible until you draw over them.