我有一个应用程序正在从用户接收文本然后将其放入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();
}
}
答案 0 :(得分:1)
程序就像kdiff3,它读取用户输入,这是一个配置文件,然后对其进行颜色编码以便于查看。
所以不要使用HTML。所有的时间都花在解析HTML上。
只需使用带有属性的简单文本即可。那就是使用JTextPane和颜色代码你想要的文本。
我已经在几秒钟内对9600行Java源文件进行了语法高亮显示。由于将文本解析为令牌,所以逻辑会更复杂。
阅读Text Component Features上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) {}