簡體   English   中英

JLabel setText 花費太多時間

[英]JLabel setText is taking too much time

我有一個應用程序從用戶那里接收文本,然后將其放入 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) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM