File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JScrollPane  for JPanel Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JScrollPane  for JPanel" Watch "JScrollPane  for JPanel" New topic

JScrollPane for JPanel

chris liao

Joined: Jul 24, 2005
Posts: 27
I want to add many buttons on a panel with gridlayout,
When the count of buttons reach some number, I hope that a JScrollPane
can appear. I have tried, but no result ! please help me !

Below is mu key source:

JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
JScrollPane scroll= new JScrollPane(panel);
scroll.getViewport().add(panel, null);

for (int i=0;i<100;i++){
panel.add(new Button(""+i));

chris liao

Joined: Jul 24, 2005
Posts: 27
Please help me ! It is very important to me, if not solve the problem,
maybe i will lost my work!

Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
it's a weekend, we are not all just waiting here to pounce on every post.

read this to understand it a bit better next time you have a problem.

now, onto your problem.

the scrollbars will appear when the preferred size of the scrollpane is less
than that of it's content.

so, if the scrollpane is added directly to the frame/contentPane,
its preferred size will be determined by the size of the frame/contentPane.

if the scrollpane is added to a panel, and the panel added to the frame/contentPane,
you will need to set a preferred size for the scrollPane
scrollPane.setPreferredSize(new Dimension(100,100));

where (100,100) is anything you want.

sample code here - compile/run 3 times for the various options

if you still have problems, post a sample program, one that we can
copy/paste/compile/run and see it not working.
I agree. Here's the link:
subject: JScrollPane for JPanel
jQuery in Action, 3rd edition