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.


 
[st_adsense]  

JTextArea constructors class:
JTextArea constructors
Description
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.
[st_adsense]  

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

public class TextAreaTest implements ActionListener
{
  JLabel l1, l2;
  JTextArea text;
  
  TextAreaTest()
  {
    JFrame f = new JFrame();
    
    l1 = new JLabel();
    l1.setBounds(45,175,100,30);
    
    l2 = new JLabel();
    l2.setBounds(150,175,100,30);
    
    text = new JTextArea();
    text.setBounds(15,20,250,150);
    
    JButton btn = new JButton("Counting words");
    btn.setBounds(50,210,180,30);
    btn.addActionListener(this);
    
    f.add(text);
    f.add(l1);
    f.add(l2);
    f.add(btn);
    
    f.setSize(300,300);
    f.setLayout(null);
    f.setVisible(true);
  }
  
  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();
  }
}

Output:


[st_adsense] 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 *