Thursday, July 8, 2010

How to use Swing Scroll Panes  

0 comments

A Scroll Pane is a component like JFrame or JPanel which is used to add other components but Scroll Pane has a Scroll Bar Associated with it which is a unique characteristic of this component Container.Scroll Panes are implemented in swing by JScrollPane class ,which extends JComponent class.Scroll Bar is either Vertical or Horizontal and they are used in Scroll Panes as needed.Like if you want to display the Scroll Bars all the time then you may use them always and also you might choose them to show up when container overflows.

Constructors used to create the Scroll Pane in Swings are :-

JScrollPane(Component cmp)
JScrollPane(int vert, int horiz)
JScrollPane(Component cmp, int vert, int horiz) 

Remember:- A window can not be added to a Scroll Pane like JFrame cannot be added to a JScrollPane,but JPanel and other similar containers can be used which are not windows.

In above constructors cmp is the component to be added on the ScrollPane.vert and horiz are the integer constants that are defined when the horizontal or vertical ScrollBars are shown in the ScrollPane.These constants are defined in ScrollPaneConstants interface.

Some example constants are :-

1.VERTICAL_SCROLLBAR_ALWAYS (Always shows up vertical scrollbar) 2.VERTICAL_SCROLLBAR_AS_NEEDED(Shows up vertical Scrollbar when needed) 3.HORIZONTAL_SCROLLBAR_ALWAYS (Always shows up horizontal scrollbar)4.HORIZONTAL_SCROLLBAR_AS_NEEDED(Shows up horizontal Scrollbar when needed)

Lets take a look at following example which lets you learn how to create and use JScrollPanes in your applications.

import java.awt.*;
import javax.swing.*;

public class Scrollpanedemo extends JFrame
{
public Scrollpanedemo()
{
JFrame frm = new JFrame("Scroll Pane demo");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(20,5));
for(int i=0;i<100;i++)
{
panel.add(new JButton("Button no. " + (i+1)));
}
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(panel,v,h);
frm.getContentPane().add(jsp);
frm.setBounds(400,200,380,310);
frm.setVisible(true);
}

public static void main(String a[])
{
new Scrollpanedemo();
}
}

In the above example we create a frame and add a scrollpane over it.Then we create a panel which contains all the components and add it to the scrollpane.We have used the AS_NEEDED constants since we want to show that when our scrollpane overflows then the Scroll Bars shows up.



What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



Extension Factory Builder