0

I have the next code:

public class MyScroll extends JFrame {

    public MyScroll() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        panel.setLayout(null);

        for (int i = 0; i < 10; i++) {
            JButton b = new JButton("Hello-" + i);
            b.setBounds(0, i * 50, 100, 45);
            panel.add(b);

            b.setLayout(null);
        }

        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(50, 30, 100, 325);

        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.setBackground(Color.BLUE);
        contentPane.add(scrollPane);

        contentPane.setLayout(null);

        setContentPane(contentPane);
        pack();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}

And, it is rendering this:

enter image description here

As you can see, the vertical and horizontal scroll aren't working, but both are defined and are displaying inside the JPanel.

Can someone explain me what am I doing wrong?

This code is based on this one: Scrolling a JPanel But, the is not working at the moment to use the verticall scrolling

TT.
  • 15,774
  • 6
  • 47
  • 88
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157

1 Answers1

0

Can someone explain me what am I doing wrong?

panel.setLayout(null);

Don't use a null layout.

The scrollbars will only appear automatically when the preferred size of the component added to the scrollpane is greater than the size of the scrollpane.

It is the job of the layout manager to determine the preferred size of the panel. Since you don't use a layout manager the preferred size isn't calculated.

So the solution is to use a Layout Manager. Maybe vertical BoxLayout.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • If I remove this line, the controls are rendered horizontally. If I use the explicit location to make them vertically, are still in horizontal position – Benjamin RD Mar 17 '19 at 20:51
  • 1
    `If I remove this line,` - did you read the rest of the answer??? `If I remove this line, the controls are rendered horizontally.` - because the default layout manager is the FlowLayout. – camickr Mar 17 '19 at 20:52
  • You right! I did a change using `BoxLayout`. With this line `panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));` is now working! Thanks – Benjamin RD Mar 17 '19 at 20:54