How do I set and get the contents of JTextArea?

To set and get the contents of a JTextArea you can use the setText(String text) and getText() methods. In the code below we create a JTextArea and sets its contents after we create a new instance of JTextArea. To get the contents we use the action on a button. When the button is pressed the contents of the JTextArea is read using the getText() method. This method return a String object.

package org.kodejava.example.swing;

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

public class TextAreaGetContent extends JPanel {
    public TextAreaGetContent() {

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        final JTextArea textArea = new JTextArea();

        // Set the contents of the JTextArea.
        String text = "The quick brown fox jumps over the lazy dog.";

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));

        JButton button = new JButton("Get Contents");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Get the contents of the JTextArea component.
                String contents = textArea.getText();
                System.out.println("contents = " + contents);

        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);

    public static void showFrame() {
        JPanel panel = new TextAreaGetContent();

        JFrame frame = new JFrame("JTextArea Demo");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

The output of the code snippet above is:

Set and Get the Content of JTextArea

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.