Skip to content

How can I add a scroll bar to a text area?

Please, anyone, tell me how to add the scrollbar to a JTextArea. I tried out many things. but still not able to get it. I copied some codes related to the text area.

public class main extends JPanel {
    private JTextArea jcomp1;

    public main() {
         jcomp1 = new JTextArea(5, 5);
         setPreferredSize(new Dimension(944, 574));
        // setPreferredSize (new Dimension (1024, 1080));
        setLayout(null);

        //add components
        
        add(jcomp1);
        jcomp1.setBounds(110, 165, 330, 300);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Paraphrasing Tool");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new main());
        frame.pack();
        frame.setVisible(true);
    }
}

Answer

Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Netbeans section.

As Andrew said, you have to place the JTextArea inside of a JScrollPane, then place the JScrollPane inside of a JPanel with a Swing layout. I used a BorderLayout.

Here’s the GUI after I typed some lines.

enter image description here

Here’s the complete runnable code.

import java.awt.BorderLayout;
import java.awt.Insets;

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

public class JTextAreaExample extends JPanel {

    private static final long serialVersionUID = 1L;
    
    private JTextArea jcomp1;

    public JTextAreaExample() {
        this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        this.setLayout(new BorderLayout());
        jcomp1 = new JTextArea(5, 30);
        jcomp1.setMargin(new Insets(5, 5, 5, 5));
        JScrollPane scrollPane = new JScrollPane(jcomp1);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Paraphrasing Tool");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
                frame.add(new JTextAreaExample(), BorderLayout.CENTER);
                
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }

}