In a JTextPane the performance of highlighting a text with ~50000 lines is very slow. Do I have any chance to increase the preformance?
Here is a SSCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextFieldUnicode {
private JTextPane textPane;
private JTextField textField;
private Document doc;
private Highlighter hilit = new DefaultHighlighter();
private Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
private TextFieldUnicode() throws BadLocationException {
this.textPane = new JTextPane();
this.textField = new JTextField();
this.doc = new DefaultStyledDocument();
generateSomeText();
addTextFieldListener();
createAndShowGUI(textField);
} //end of constructor
private void generateSomeText() throws BadLocationException {
for(int i=0;i<=50000;i++) {
doc.insertString(doc.getLength(), "hello world, hello stackoverflow, here is some generated text "+i+"\n", null);
}
textPane.setDocument(doc);
}
//here, the text will be highlighter after a search query is inserted
private void addTextFieldListener() {
textField.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
float start = System.nanoTime(); //start meausuring time
textPane.setHighlighter(hilit);
String query = textField.getText();
String text = textPane.getText();
text = text.replaceAll("[\n]+", "");
if(text != null) {
int index = text.indexOf(query); //get index of word
int len = query.length(); //get length of word
while ( index >= 0 ) {
try {
textPane.getHighlighter().addHighlight(index, index+len, painter);
} catch (BadLocationException e) {
e.printStackTrace();
}
index = text.indexOf(query, (index+len));
}
}
float stop = System.nanoTime(); //stop meausuring time
System.out.println("time="+(stop-start)/1000000000+"s");
}
});
}
private void createAndShowGUI(JTextField textField) {
//Create and set up the window.
JFrame frame = new JFrame("TextFieldDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField, BorderLayout.NORTH);
frame.add(new JScrollPane(textPane), BorderLayout.CENTER);
frame.setSize(new Dimension(600, 600));
frame.setVisible(true);
}
public static void main(String[] args) throws BadLocationException {
new TextFieldUnicode();
}
}
And here is a screenshot of my example: it takes approx. 2 seconds on an i5@1,9GHz/8GByte Ram when I highlight the e letters. Any suggestions of how to do it in a better way?