JLabel setText花费了太多时间



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

text1.setText( arg2 );

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

https://stackoverflow.com/questions/23951118/jtextarea-settextverylongstring-is-taking-too-much-time

但我找不到一种方法来解决这个问题。有解决方案吗?

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

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

该程序类似于kdiff3,它读取用户输入,这是一个配置文件,然后对其进行颜色编码以便于查看。

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

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

我已经在几秒钟内对一个9600行的Java源文件进行了语法高亮显示。由于将文本解析为令牌,因此这种逻辑将更加复杂。

阅读Swing教程中关于文本组件功能的一节,了解如何使用属性的工作示例。

你的基本逻辑是这样的:

// 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) {}