java - 如何在java swing中的jtextarea顶部插入或追加新行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12565358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:23:49  来源:igfitidea点击:

how to insert or append new line on top of the jtextarea in java swing?

javaswingappendjtextarea

提问by sandybarasker

how to insert or append new line on top of the jtextarea in java swing ? i want to to append jtextarea and add the new line on top of the jtextarea please help me how to do this.

java - 如何在java swing中的jtextarea顶部插入或追加新行? 我想附加 jtextarea 并在 jtextarea 顶部添加新行,请帮助我如何做到这一点。

采纳答案by Guillaume Polet

Your best option is to directly modify the underlying Documentof the JTextArea.

最好的选择是直接修改底层DocumentJTextArea

Here is a small demonstration of this:

这是一个小演示:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;

public class TestTextArea {

    private void initUI() {
        JFrame frame = new JFrame("test");
        final JTextArea textarea = new JTextArea(24, 80);
        JButton addText = new JButton("Add line");
        addText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    textarea.getDocument().insertString(0, "New line entered on " + new Date() + "\n", null);
                } catch (BadLocationException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(textarea));
        frame.add(addText, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                new TestTextArea().initUI();
            }
        });
    }

}

回答by Dan D.

You can do this:

你可以这样做:

textArea.setText("The new text\n" + textArea.getText());

Or, an even better solution would be this:

或者,更好的解决方案是:

try {
  textArea.getDocument().insertString(0, "The new text\n", null);
} catch (BadLocationException e) {
  e.printStackTrace();
}

回答by AlexR

textArea.setText("this is new line" + "\n" + textArea.getText())

textArea.setText("this is new line" + "\n" + textArea.getText())