繁体   English   中英

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

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

如何在java swing中的jtextarea顶部插入或追加新行? 我想追加jtextarea并在jtextarea之上添加新行,请帮我解决这个问题。

你可以这样做:

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

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

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

您最好的选择是直接修改JTextArea的基础Document

这是一个小例子:

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();
            }
        });
    }

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM