A scroll pane is a container that represents a small area to view other component. If the component is larger than the visible area, scroll pane provides horizontal and/or vertical scroll bars automatically for scrolling the components through the pane. A scroll pane is an object of the JScrollPane class which extends JComponent.
Some of the constructors defined by JScrollPane class are as follows.
JSrollPane ()
JScrollPane(Component component)
JScrollPane(int ver, int hor)
JScrollPane(Component component, int ver, int hor)
where,
component is the component to be added to the scroll pane
ver and hor specify the policies to display the vertical and horizontal scroll bar, respectively. Some of the standard policies are:
HORIZONTAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED, VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_AS_NEEDED
Note: JScrollPane is a lightweight container.
import javax.swing.*;
import java.awt.*;
public class JavaExampleJScrollPane extends JFrame
{
private JPanel Pnl = new JPanel();
private JScrollPane Scrl = new JScrollPane(Pnl,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
private JLabel Lbl = new JLabel("JScrollPane in Java Swing Example");
private Font font = new Font("Arial", Font.PLAIN, 20);
private Container cntnr;
public JavaExampleJScrollPane()
{
super("JScrollPane in Java Swing Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cntnr = getContentPane();
Lbl.setFont(font);
cntnr.add(Scrl);
Pnl.add(Lbl);
}
public static void main(String[] args)
{
final int WIDTH = 180;
final int HEIGHT = 100;
JavaExampleJScrollPane Scroll = new JavaExampleJScrollPane();
Scroll.setSize(250,300);
Scroll.setVisible(true);
}
}