jcb1996
jcb1996

Reputation: 1

Adding JScrollPane to GridBagLayout

Everytime I click a button in my program, I add 5 new rows to the JPanel. Eventually, the rows overflow and I would like to add a JScrollPane so I can scroll down and see the new rows.

I know how to get it working for a TextArea but I can't seem to figure out how to make it work when I have a GridBagLayout. Below, I will attach the code for setting up my panels.

    JPanel panelMain = new JPanel();
    getContentPane().add(panelMain);

    JPanel panelForm = new JPanel(new GridBagLayout());
    panelMain.add(panelForm);

    JScrollPane scrollpane = new JScrollPane(panelForm);
    panelMain.add(scrollpane);

When I run, my code I get a box enclosing the GridBagLayout, but the scrollpane is nowhere to be seen.

Upvotes: 0

Views: 651

Answers (1)

camickr
camickr

Reputation: 324098

JPanel panelMain = new JPanel();
getContentPane().add(panelMain);

You would typically add the scroll pane directly to the frame. There is no need for the "panelMain".

panelMain.add(panelForm);

That line is not needed. A component can only belong to a single parent. You later add "panelForm" to the scrollpane.

So the basic code would be:

JPanel panelForm = new JPanel(new GridBagLayout());
JScrollPane scrollpane = new JScrollPane(panelForm);
frame.add(scrollpane);

but the scrollpane is nowhere to be seen.

The scrollbars only appear when needed by default. Adding empty panels will not cause the scrollbar to be displayed. Click on your button a few times and add your child components to the "panelForm" using the appropriate GridBagConstraints. You will then need to use:

panelForm.revalidate();
panelForm.repaint();

The revalidate() causes the layout manager to be invoked so the scrollpane can determine is scrollbars are required or not.

Upvotes: 1

Related Questions