Reputation: 57
So, I'm trying to make a little program to display chat logs from a certain app in a custom way. I alredy built my GUI, and I can read the messages from the .txt file. My problem is, when I print them on the console, the program takes about 1.5 seconds to process the 17k line file. But, when I try to show the text on the GUI, it takes around a minute and a half, and I have no idea why.
To read the text from the file, I'm using a BufferedReader. And to show the text on a JTextArea, and all I'm doing is the following:
JTextArea.append(myString+"\n");
My test file is around 1,000,000 characters long, if that's any help. I'd really like to know what's happening, and maybe some advice on how to fix it. Thanks in advance.
Upvotes: 1
Views: 69
Reputation: 7008
Use a StringBuilder to build the String and then just call setText() once one the TextArea so you don't force a repaint of the area for each line.
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
JFrame frame =new JFrame();
JTextArea area = new JTextArea();
JScrollPane pane = new JScrollPane(area);
frame.add(pane);
frame.setPreferredSize(new Dimension(400,400));
frame.pack();
frame.setVisible(true);
long t1 = System.currentTimeMillis();
for(int i = 0; i < 100000; i++) {
area.append(i+"\n");
}
long t2 = System.currentTimeMillis();
System.out.println("(t2-t1) = " + (t2-t1));
StringBuilder sb = new StringBuilder();
long t3 = System.currentTimeMillis();
for(int i = 0; i < 100000; i++) {
sb.append(i+"\n");
}
long t4 = System.currentTimeMillis();
area.setText(sb.toString());
System.out.println("(t4-t3) = " + (t4-t3));
});
}
prints:
(t2-t1) = 2871
(t4-t3) = 26
The first time difference was measured with JTextArea.append() the second with StringBuilder.append() followed by JTextArea.setText().
Upvotes: 1