JScrollPane in Java

A JScrollPane in Java is a component that provides a scrollable view of a larger component, such as a JTextArea or JList.

First, let’s understand why JScrollPane is needed in Java.

To understand this, we need to understand the following code and it’s output.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class JScrollPaneDemo {
	public static void main(String[] args) {
		SwingUtilities.invokeLater(() -> createAndShowGUI());
	}

	private static void createAndShowGUI() {
		JFrame frame = new JFrame("JScrollPane Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 300);

		JTextArea textArea = new JTextArea(20, 40);
		for (int i = 0; i < 50; i++) {
			textArea.append("Line " + (i + 1) + "\n");
		}

		frame.add(textArea);

		frame.setVisible(true);
	}
}

In the example above, we’ve created a JTextArea without adding a scroll bar. It has 20 rows but we are adding 50 lines.

The output of the above program is given below:

JScrollPane in Java JText Area without JScrolPane

If you notice in the output, it shows only a few lines not all lines. Neither does it allow us to scroll up and down.

To fix this issue let’s add a scrollbar and see the output.

Code with JScrollBan

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class JScrollPaneDemo {
	public static void main(String[] args) {
		SwingUtilities.invokeLater(() -> createAndShowGUI());
	}

	private static void createAndShowGUI() {
		JFrame frame = new JFrame("JScrollPane Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 300);

		JTextArea textArea = new JTextArea(20, 40);
		for (int i = 0; i < 50; i++) {
			textArea.append("Line " + (i + 1) + "\n");
		}


        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        frame.add(scrollPane);

		frame.setVisible(true);
	}
}

Now, see the output below:

JScrollBar in Java