java - 如何在java swing中的jtextarea顶部插入或追加新行? [英] how to insert or append new line on top of the jtextarea in java swing?

查看:54
本文介绍了java - 如何在java swing中的jtextarea顶部插入或追加新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

Your best option is to directly modify the underlying Document of the JTextArea.

这是一个小演示:

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

}

这篇关于java - 如何在java swing中的jtextarea顶部插入或追加新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆