JLabel setText 花费太多时间

JLabel setText is taking too much time

我有一个应用程序从用户那里接收文本,然后将其放入 jLabel。它对文本进行了一些处理,所以我认为这是一个问题,但经过一些故障排除后,我隔离了程序中最耗时的部分。

text1.setText( arg2 );

其中 arg2 是一个长字符串。在测试中我一直在使用 9000 行。它也被格式化为 HTML。我认为这可能需要一些时间,几秒钟,但要花费大量时间,3 分 35 秒。我在这里发现了一些与 jTextArea 有类似问题的问题:

但我找不到将该解决方案应用于此问题的方法。有解决办法吗?

编辑 - 我的代码如下。请注意,为了简洁起见,我已经删减了字符串的中间部分。

import java.io.*;
import java.lang.*;
import javax.swing.*;
public class jLabelIssue {
    public static void main( String[] args ) {
        final JFrame frame = new JFrame( "Comparinger use this to compare things and stuff" );
        frame.setSize(268, 150);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible( true );
        JLabel text1 = new JLabel( );
        frame.add( text1 );
        arg2 = 
        "<HTML><font color=black>" + 
        "a<br/>" +
        "a<br/>" +
        "a<br/>" +
        //... 9000 more lines of this ...
        "a<br/>" +
        "a<br/>" +
        "a<br/>" +
        "</font></HTML>";
        text1.setText( arg2 );
        frame.repaint();
    }
}

The program is like kdiff3, it reads the user input, which is a configuration file, then color codes it for easy viewing.

所以不要使用 HTML。所有的时间都花在解析 HTML.

只需使用带有属性的简单文本。那就是使用 JTextPane 并根据需要对文本进行颜色编码。

我在几秒钟内完成了 9600 行 Java 源文件的语法高亮显示。而且由于将所有文本解析为标记,该逻辑会更加复杂。

阅读 Swing 教程中关于 Text Component Features 的部分,了解使用属性的工作示例。

你的基本逻辑是这样的:

// Define the basic colors you want to use:

SimpleAttributeSet colorCode1 = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);

SimpleAttributeSet colorCode2 = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.YELLOW);

//  Add some text

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

try
{
    doc.insertString(doc.getLength(), "\nA line of text", colorCode1);
    doc.insertString(doc.getLength(), "\nAnother line of text", colorCode2);
}
catch(Exception e) {}