I have a very long string which I get from a book. I display it in a JTextArea by using the setText() method. It freezes the UI and takes a lot of time. How do I get around that?
Here is as SSCCE:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class SSCCE extends JFrame {
JTextArea textArea;
public SSCCE() {
String text = buildLongString(400000);
textArea = new JTextArea();
textArea.setText(text);
textArea.setLineWrap(true);
add(new JScrollPane(textArea));
setSize(400, 350);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private String buildLongString(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
builder.append("x");
}
return builder.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SSCCE();
}
});
}
}