How do I create a single line JTextArea?

The following example will show you how to create a single line JTextArea. A single line means that you cannot insert a new line in the text area. When pressing the enter key it will be replaced by a space.

This can be done by putting a property called filterNewlines and set its value to Boolean.TRUE into the document model of the JTextArea.

package org.kodejava.swing;

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

public class SingleLineTextArea extends JFrame {
    private SingleLineTextArea() {

    public static void main(String[] args) {
                () -> new SingleLineTextArea().setVisible(true));

    private void initialize() {
        setSize(500, 200);
        setTitle("Single Line Text Area");
        setLayout(new BorderLayout());

        final JTextArea textArea = new JTextArea();

        // Filter a new line, pressing enter key will be replaced
        // with a space instead.

        JScrollPane scrollPane = new JScrollPane(textArea);

        // Pressing the Save button print out the text area text
        // into the console.
        JButton button = new JButton("Save");
        button.addActionListener(e -> System.out.println(textArea.getText()));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);

The screenshot of the result of the code snippet above is:

Single Line JTextArea Demo