JTextArea Example Java Swing

April 2, 2013 | Swing
The limitation of JTextField is that we can enter or display the text in one line only. This limitation is overcome with JTextArea. In JTextArea, we can enter or display any number of lines of text. We can make a text area not to be used by the user by using setEditable(false) method.

Like class JTextField, class JTextArea inherits from JTextComponent, which defines common methods for JTextField, JTextArea and several other text-based GUI components.

In the following JTextArea example, the selected text in the text area is displayed in JOptionPane showMessageDialog box. The text is displayed when the button, display is clicked.

import java.awt.*;
import java.awt.event.*;     
import javax.swing.*;    

public class JTextAreaDemo extends JFrame implements ActionListener   
{  
  JButton display;                       // a button to raise an event
  JTextArea tf ;                         // a text area that contains some text
  public JTextAreaDemo()   		  
  {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    String str = "Java is simple to practice.\nBut is ocean.\nRequires lot of practice\n to become a good programmer.\nWhenever free, open the Java API and browse the methods in each class.";
    display = new JButton("Display");

    tf = new JTextArea(str, 10, 30);     // text area of size 10 rows and 30 columns

    display.addActionListener(this);
   
    c.add(tf);
    c.add(display);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    // to close the JFrame window
    setTitle("Learning JTextArea");
    setSize(400,300);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    String s1 = tf.getSelectedText();
    JOptionPane.showMessageDialog(null, s1,  "Practcing JTextArea", JOptionPane.PLAIN_MESSAGE);
  }
  public static void main(String args[])
  {
    new JTextAreaDemo();
  }
}

JTextArea

tf = new JTextArea(str,10,30);

The above statement creates a JTextArea object, tf that displays 10 lines and each line containing 30 characters. By default, the string str is displayed in the text area. If extra lines and columns are added, automatically scorllbars will be added.

String s1 = tf.getSelectedText();

The getSelectedText() method returns the selected portion of the text. There is one more method getText() that returns all the text present in the text area.

The color of JTextArea can be changed with setBackground() and setForeground() methods.

The text in the text area can be clear with setText("").