CrazyProgrammer
CrazyProgrammer

Reputation: 544

ScrollBar is not working when Layout is null

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);
    }
}

Upvotes: 1

Views: 770

Answers (1)

Angelus
Angelus

Reputation: 46

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

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

for example

Upvotes: 3

Related Questions