1

Scroolbar doesnt appear when the layout set to null. How to get the scrollbar inside the panel? Is there any other way to achieve it. I want to get the scroll bar in the scrollPane

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollBarExample {

    public static void main(String... args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setLayout(null);
        for (int i = 0; i < 10; i++) {
            JButton jbutton = new JButton("Hello-" + i);
            jbutton.setBounds(i * 100, i*30, 100, 40);
            panel.add(jbutton);
        }
        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setBounds(50, 10, 320, 100);
        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.add(scrollPane);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
CrazyProgrammer
  • 544
  • 8
  • 29
  • 1
    I hate to sound like a jerk, but isn't the obvious solution then to either remove 'panel.setLayout(null);' or to not put a null value as the LayoutManager? – mbw Aug 13 '14 at 15:49

1 Answers1

3

Without Layout-Manager you need to set the Preferred-Size of the Panel by hand

panel.setPreferredSize(new Dimension(500, 500));

for example

Angelus
  • 46
  • 2
  • 1
    [Don't use `setPreferredSize()` when you really mean to override `getPreferredSize()`](http://stackoverflow.com/q/7229226/230513). – trashgod Aug 13 '14 at 16:10