Java Swing GUI

JTextArea – Java Swing – Example

In this tutorial, we are going to see an example of JTextArea in Java Swing. JTextArea is part of the Java Swing package. It represents an area on several lines that displays text. It is used to edit text. JTextArea inherits from the JComponent class. The text in JTextArea can be set to different available fonts. The text area can be customized according to the user’s needs.


JTextArea constructors class:
JTextArea constructors
JTextArea() Builds a new empty text area.
JTextArea(String s) Builds a new text area with a given initial text.
JTextArea(int row, int column) Builds a new text area with a given number of rows and columns.
JTextArea(String s, int row, int column) Builds a new text area with a given number of rows and columns and a given initial text.


Commonly used methods:
  • append(String s): adds the given string to the text in JTextArea.
  • getLineCount(): gets the number of lines of text in the JTextArea.
  • setFont(Font f): sets the font of JTextArea to the given font.
  • setColumns(int c): sets the number of columns in JTextArea to a given integer.
  • setRows(int r): sets the number of lines in JTextArea to a given integer.
  • getColumns(): gets the number of columns in JTextArea.
  • getRows(): gets the number of lines in JTextArea.

Example of JTextArea in Java Swing:
import javax.swing.*;
import java.awt.event.*;

public class TextAreaTest implements ActionListener
  JLabel l1, l2;
  JTextArea text;
    JFrame f = new JFrame();
    l1 = new JLabel();
    l2 = new JLabel();
    text = new JTextArea();
    JButton btn = new JButton("Counting words");
  public void actionPerformed(ActionEvent e)
    String str = text.getText();
    String words[] = str.split("\\s");
    l1.setText("Cords: "+ words.length);
    l2.setText("Character: "+ str.length());
  public static void main(String[] args) {
    new TextAreaTest();


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *