Java JScrollPane

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component or a component whose size can change dynamically.

Constructors

Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the scroll pane's client. The two int parameters, when present, set the vertical and horizontal scroll bar policies (respectively).
JScrollPane(Component)
JScrollPane(int, int)
JScrollPane(Component, int, int)

Useful Methods

Modifier Method Description
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int parameter specifies which corner and must be one of the following constants defined in ScrollPaneConstants: UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER, LOWER_TRAILING_CORNER, UPPER_LEADING_CORNER, UPPER_TRAILING_CORNER.
Component getCorner(String)
void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example

  1. import java.awt.FlowLayout;  
  2. import javax.swing.JFrame;  
  3. import javax.swing.JScrollPane;  
  4. import javax.swing.JtextArea;  
  5.   
  6. public class JScrollPaneExample {  
  7.     private static final long serialVersionUID = 1L;  
  8.   
  9.     private static void createAndShowGUI() {  
  10.   
  11.         // Create and set up the window.  
  12.         final JFrame frame = new JFrame("Scroll Pane Example");  
  13.   
  14.         // Display the window.  
  15.         frame.setSize(500500);  
  16.         frame.setVisible(true);  
  17.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  18.   
  19.         // set flow layout for the frame  
  20.         frame.getContentPane().setLayout(new FlowLayout());  
  21.   
  22.         JTextArea textArea = new JTextArea(2020);  
  23.         JScrollPane scrollableTextArea = new JScrollPane(textArea);  
  24.   
  25.         scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  26.         scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
  27.   
  28.         frame.getContentPane().add(scrollableTextArea);  
  29.     }  
  30.     public static void main(String[] args) {  
  31.   
  32.   
  33.         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  34.   
  35.             public void run() {  
  36.                 createAndShowGUI();  
  37.             }  
  38.         });  
  39.     }  
  40. }  

Output:

Java JScrollpane