JScrollPane

Create JScrollPane example

In this example we are going to see how to create a JScrollPane container in a Java Desktop Application. This is one of the most important components in a GUI application, especially when your client code has to handle and to display a large amount of data.

It is very simple to create a JScrollPane. All you have to do is:

  • Create a new JFrame.
  • Create a JTextArea.
  • Call new JScrollPane(textArea) to create a scrollable Text Area. Remember that JScrollPane is a container and you can add any component you want to it to make it scrollable.
  • Use setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy to set the vertical and horizontal scroll bar policies.

Let’s see the code:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.javacodegeeks.snippets.desktop;
 
import java.awt.FlowLayout;
 
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
public class CreateJScrollPaneExample {
 
    private static final long serialVersionUID = 1L;
 
    private static void createAndShowGUI() {
 
        // Create and set up the window.
        final JFrame frame = new JFrame("Scroll Pane Example");
 
        // Display the window.
        frame.setSize(200, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        // set flow layout for the frame
        frame.getContentPane().setLayout(new FlowLayout());
 
        JTextArea textArea = new JTextArea(5, 5);
        JScrollPane scrollableTextArea = new JScrollPane(textArea);
 
        scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
 
        frame.getContentPane().add(scrollableTextArea);
 
    }
 
    public static void main(String[] args) {
 
  //Schedule a job for the event-dispatching thread:
 
  //creating and showing this application's GUI.
 
  javax.swing.SwingUtilities.invokeLater(new Runnable() {
 
public void run() {
 
    createAndShowGUI();
 
}
 
  });
    }
 
}

 
This was an example on how to create a JScrollPane.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest


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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button