Title: Scrollbar is not appearing in a JPanel
Tags: java;swing;jpanel;jscrollpane
Question: import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
class Test
public Test()
JFrame f = new JFrame();
f.setSize(800,800);
f.setLayout(new FlowLayout());
JPanel s = new JPanel();
s.setLayout(new BoxLayout(s,BoxLayout.PAGE_AXIS));
JLabel m = new JLabel("D");
JLabel m1 = new JLabel("D1");
JLabel m2 = new JLabel("D1");
JLabel m3 = new JLabel("D1");
JLabel m4 = new JLabel("D1");
JLabel m5 = new JLabel("D1");
JLabel m6 = new JLabel("D1");
JLabel m7 = new JLabel("D1");
JLabel m8 = new JLabel("D1");
s.add(m);
s.add(m1);
s.add(m2);
s.add(m3);
s.add(m4);
s.add(m5);
s.add(m6);
s.add(m7);
s.add(m8);
JScrollPane scroll = new JScrollPane(s);
//scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setViewportBorder(new LineBorder(Color.RED));
f.add(scroll);
f.setVisible(true);
public static void main(String args[])
Test t = new Test();
Everything is ok,but the Scroll is not showing (JScollPane is appearing) .. and is there a better way to do this ? I mean - the proper way to show a JScrollPane in a panel ...... ?
It's showing like this
Comment: The JScrollPane is showing in the image that you posted. Can you clarify what the problem with your current results is?

Comment: it works for me

Here is the accepted answer: Scrollbars appear when the preferred size of the component added to the scollpane is greater than the size of the scrollpane.
JScrollPane scroll = new JScrollPane(s);
scroll.setPreferredSize(new Dimension(100, 50));
Scroll pane will expand its height as you add elements into it, unless you set the preferred size.
Comment for this answer: Yes !! Thank you @richersoon


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:12/23/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><swing><jpanel><jscrollpane>', 'Title': 'Scrollbar is not appearing in a JPanel', 'ViewCount': 1053, 'id': 41303000, 'user_AboutMe': '', 'user_AccountId': 9895271.0, 'user_DisplayName': 'Hasan', 'user_Reputation': 49.0, 'user_Views': 10.0, 'user_id': 7327001.0}}