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.swing;

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

public class TextAreaGetContent extends JPanel {
    public TextAreaGetContent() {
        initializeUI();
    }

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

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaGetContent::showFrame);
    }

    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.";
        textArea.setText(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

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

        JButton button = new JButton("Get Contents");
        button.addActionListener(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);
    }
}

The output of the code snippet above is:

Set and Get the Content of JTextArea

Wayan

Leave a Reply

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