Search code examples
performancejtextpane

Improve the performance of JTextPane


I have a String array with approximately 10000 elements of text that I want to put in a JTextPane. Unfortunately, it is too slow and I don't have any ideas of how to increase the performance. In particular, it takes very long when I use Chinese or Arabic letters/fonts.

It takes ~20seconds to load every arabic text from string array into the textpane on i5 @ 2Ghz.

Here is my code:

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.*;

public class JTextPaneTest {
    private JTextPane textPane = new JTextPane();
    Document doc = new DefaultStyledDocument();
    private JPanel panel = new JPanel();

    //constructor
    JTextPaneTest() {               
        for(int i=0;i<10000;i++) {
            try {
                doc.insertString(doc.getLength(), i+" hello world!\n", null);
            } catch (BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }               
        }
        textPane.setDocument(doc);
        createWindow();
    }

    public void createWindow() {
        JFrame frame = new JFrame();
        frame = new JFrame("frame");     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().add(new JScrollPane(textPane), BorderLayout.CENTER);
        frame.setVisible(true);         
    }

    public static void main(String[] args) {
        System.out.println("start...");
        float startTime = System.nanoTime();
        new JTextPaneTest();
        float stopTime = System.nanoTime() - startTime;
        System.out.println("elapsed time main: "+stopTime/1000000000+ "s");
    }
}

In the example above, I used "Hello world!" instead of string array to make the code more legibly.

How could I improve the algorithm? Any alternative ideas?

Thanks


Solution

  • The problem could be long LabelViews measuring.

    Suppose text has 10000 chars it's measured to fit available width and piece of the label is created (let's say 100 chars) Then 9900 chars again measured etc. etc. to create 100 of 100 chars labels.

    You can create artificial break to avoid such a big texts measuring.

    See here http://java-sl.com/JEditorPanePerformance.html