Java如何创建单行JTextArea?

以下示例将向您展示如何创建单行JTextArea。单行表示您不能在文本区域中插入新行。当按下回车键时,它将被一个空格代替。

这可以通过将名为的属性filterNewlines并将其值设置Boolean.TRUE为的文档模型来完成JTextArea。

package org.nhooo.example.swing;

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

public class SingleLineTextArea extends JFrame {
    private SingleLineTextArea() {
        initialize();
    }

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

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);

        // 过滤新行,按回车键将被替换
        // 用空格代替。
        textArea.getDocument().putProperty("filterNewlines",
            Boolean.TRUE);

        JScrollPane scrollPane = new JScrollPane(textArea);

        // 按下保存按钮,打印出文本区域的文本
        // 进入控制台。
        JButton button = new JButton("Save");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(textArea.getText());
            }
        });
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SingleLineTextArea().setVisible(true);
            }
        });
    }
}

上面的代码片段的结果的屏幕截图是: