如何插入或在的Java Swing JTextArea中的顶部添加新的生产线? [英] how to insert or append new line on top of the jtextarea in java swing?

查看:215
本文介绍了如何插入或在的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.

推荐答案

您最好的选择是直接修改底层的 文件 的JTextArea

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 Swing JTextArea中的顶部添加新的生产线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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