JScrollPane Example Java Swing

JScrollPane scrolls to view the contents of the component added to it. Scrollbars are used to scroll the contents horizontally and vertically. From JDK 1.4, new methods for mouse wheel movements are added like processMouseWheelEvent(MouseWheelEvent) etc. The mouse wheel can be used to enlarge a photo by rotating the wheel in the display area.

Following example uses JScrollPane.

import javax.swing.*;  
import java.awt.event.*;  
import java.awt.*;
public class ScrollPaneDemo extends JApplet  
  public void init()  
    Container cp = getContentPane();
    // cp.setLayout( new BorderLayout()) ; not needed as container default is BorderLayout
    JPanel jp = new JPanel( ) ;
    jp.setLayout( new GridLayout( 20, 20 ) ) ;
    for(int i = 0 ; i < 20 ; i++)
       for( int j = 0 ; j < 20 ; j + +  )   
	  jp.add(new JButton("Button " + j));

    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ;

    JScrollPane js = new JScrollPane( jp, v, h ) ;
    cp.add(js, BorderLayout.CENTER) ;

Output screen of JScrollPane Example

In the above program, 400 buttons (20 rows x 20 columns) can be viewed by adding to JScrollPane. If added to a frame or panel directly (without using scroll pane), all are not visible. They are added to a panel and the panel is added to a scroll pane. Using scrollbars, all the contents can be viewed. This is the advantage with scroll pane. In the earlier program, JList is added to scroll pane.

Programmer can be choosy about the appearance of scrollbars. Other options for ScrollPaneConstants are


The above options apply to horizontal scrollbar also. The first option gives scrollbars if needed only. Needed means if the display area is more and contents are less, scrollbars are not given and if the contents are more the scrollbars are given. Never means the scrollbars are not given even if needed. Always means whether needed are not, scrollbars are given always.

1 thought on “JScrollPane Example Java Swing”

Leave a Comment

Your email address will not be published.