How to use JTextArea in Java

From our previous post, we learned how to use JLabel, JTextField and JPasswordField. In this post, we will concentrate on how to use JTextArea in Java.

JTextArea is a component used so that users can type anything just like using a notepad. You can edit the fonts including the style and sizes and also HTML.

Below is an example of a simple JTextArea.

package com.javapointers.javase;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class JTextAreaTest {
    
    JTextArea text;
    JFrame frame;
    
    public JTextAreaTest(){
        frame = new JFrame();
        text = new JTextArea(5,40);
        text.setLineWrap(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(text);
        frame.pack();
        frame.setTitle("JTextArea Test");
        frame.setVisible(true);
    }
    public static void main(String args[]){
        JTextAreaTest test = new JTextAreaTest();
    }
}

When we run our program, the UI will be like below:

Explanation:

  • text = new JTextArea(5,40);

means to create a new instance of JTextArea with an initial height of 5 and a width of 40.

  • text.setLineWrap(true);

we have set the line wrap to true so that when the cursor reaches the end of the area, it will automatically set the cursor to the next line. Setting it to false will make the characters to be displayed in just one line and some text may not be displayed.

That’s it on how to use JTextArea in Java applications. The next tutorial is about ActionListener which is being triggered or called whenever an action was made to a component.

Share this tutorial!