您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JTextArea setText(veryLongString)花费太多时间

JTextArea setText(veryLongString)花费太多时间

在与构造GUI分开的单独线程中创建DefaultStyledDocument似乎是创建巨大文本区域的最快方法。DefaultStyledDocument是线程安全的。

这是我用来测试DefaultStyledDocument的代码。我用空格创建了文本,以便换行的Swing代码有机会工作。

package com.ggl.testing;

import java.util.Random;

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

public class HugeTextArea implements Runnable {

    private DefaultStyledDocument   document;

    private JFrame                  frame;

    private JTextArea               textArea;

    public HugeTextArea() {
        this.document = new DefaultStyledDocument();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                buildLongString(400000);
            }
        };
        new Thread(runnable).start();
    }

    @Override
    public void run() {
        frame = new JFrame();
        frame.setTitle("Huge Text");
        frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

        textArea = new JTextArea(document);
        textArea.setLineWrap(true);
        frame.add(new JScrollPane(textArea));

        frame.setSize(400, 350);
        frame.setLocationRelativeTo(null);

        frame.setVisible(true);
    }

    private void buildLongString(int length) {
        Random random = new Random();
        String[] chars = { "s", "t", "a", "y", " " };
        for (int i = 0; i < length; i++) {
            try {
                document.insertString(document.getLength(),
                        chars[random.nextInt(chars.length)],
                        null);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokelater(new HugeTextArea());
    }

}
其他 2022/1/1 18:46:09 有494人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶