JScrollPane in Java with Example using NetBeans

JScrollPane in java:

The javax.swing.JScrollPane class is a container that is equipped with a scrollbar if the content is too large to be able to display it completely. Scrollbars are probably familiar to you from surfing the Internet. This is the scroll bar that should still be present on the right side of your browser window so you can read the full text by scrolling down.

In addition to the usual parameterless default constructor, the JScrollPane class also has the following constructors:


JScrollPane Constructors:

constructor description
JScrollPane(Component view) The component that is to be displayed within the JScrollPanes is passed to the constructor.
JScrollPane(Component view, int vsbPolicy, int hsbPolicy) In addition to the component to be displayed, two additional parameters are passed here with which you can control the visibility of the scrollbars. For this there is the  ScrollPaneConstants interface with the corresponding constants, which we will explain in the next table.
JScrollPane(int vsbPolicy, int hsbPolicy) As above, but without the parameter for the component.

The ScrollPaneConstants interface provides the following constants for the  vsbPolicy and hsbPolicy parameters:

constant explanation
ScrollPaneConstants.

HORIZONTAL_SCROLLBAR_AS_NEEDED

Horizontal scrollbar is only shown when it is needed.
ScrollPaneConstants.

HORIZONTAL_SCROLLBAR_NEVER

Horizontal scrollbar is never displayed.
ScrollPaneConstants.

HORIZONTAL_SCROLLBAR_ALWAYS

Horizontal scrollbar is always displayed.
ScrollPaneConstants.

VERTICAL_SCROLLBAR_AS_NEEDED

Vertical scrollbar only appears when needed.
ScrollPaneConstants.

VERTICAL_SCROLLBAR_NEVER

Vertical scrollbar is never displayed.
ScrollPaneConstants.

VERTICAL_SCROLLBAR_ALWAYS

Vertical scrollbar is always displayed.



Example: how to use JScrollPane in java using NetBeans:

First, I create a JPanel with a long text, which is wider than the dialog window. In order to be able to read the text completely, we need a scrollbar. So I create a JScrollPane object using the constructor as you can see in the constructor table above. This gets our previously created JPanel, which is to be displayed in the JScrollPane. In addition, we use the constants to specify that the JScrollPane should only have a vertical and horizontal scrollbar when they are required. In our example, only a horizontal scrollbar is needed to see the complete JLabel:

JScrollPane

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: