Working with ScrollPanes in Java

Working with ScrollPanes in Java

Scrollbars are an integral part of any interface. To show any content that extends beyond the length of a certain page, you most definitely will need a scroll pane or a scrollbar. Scrollbars also come into play when dynamically resizing a page. For example, when you contract the window size from full screen to any other size, a scrollbar immediately appears to the right and bottom of the page such that you can see all the content of that page.

How to Create a ScrollPane

As this component is part of the Java Swing Package, you will first and foremost need to import the package:

import javax.swing.*;

Once done, you can call a new ScrollPane object: JScrollPane sp = new JScrollPane();


  • JScrollPane() – This will just create a new ScrollPane object or component.
  • JScrollPane(Component) – The Component sets the scroll pane’s client.
  • JScrollPane(int, int) – The two int parameters assume the horizontal and vertical policies of the scroll pane.
  • JScrollPane (Component, int, int) – This scrollpane will have a component as well as horizontal and vertical policies.

Useful Methods

  • void setColumnHeaderView (Component) – This will set column header
  • void setRowHeaderView (Component) – Sets the row header
  • setCorner (String, Component) – This will set the specified corner as determined by the int parameter.
  • getCorner(String) – A ScrollPane has several corners like UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, and so on. This method will get the corner.


The following will demonstrate how to create a vertical and horizontal scroll pane on your application window.

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollDemo {
private static void showBar()
final JFrame frame = new JFrame(“Scroll Pane Demo”);


//We will be using a flow layout here
//Assigning the flow layout to the frame
frame.getContentPane).setLayout(new Flow Layout());

JTextArea = new JTextArea(20,20);
JScrollPane scroll = new JScrollPane(text Area);



public static void main (String args [])
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run ()


A blank window will be created with two scrollbars at the bottom and at the right of your screen just like you see on a webpage while surfing the Internet.


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.