How to retrieve and set the huge String data retrieved -- to a JTextArea in swing?
I have 2 classes -A and B.I am building a GUI for retrieving a list of files. Class B is for recursion and returns a generic List of files. Class A is for GUI and retrieves the list of files and converts each file to a string.
Now, My problem is that when i call System.out.println(SomeFileName.toString()); in Class B. the Output is BLAZING fast ! But when i retrieve the same list of files via Class A and append the output to a JTextArea -- then the processing becomes a Million times slower.
Can anybody give me a solution ? Should i use buffers ? or I was looking over, somewhere it was suggested that i use a Document for a JTextArea ! I am using NetBeans.
Class A is coded like this :
List<File> hoohoo = cr.catalog(partition);
Iterator<File> it = hoohoo.iterator();
while (it.hasNext()) {
File myf = it.next();
filesText.append(myf.toString() + NEWLINE);
}
Class B looks like this ::
public List<File> catalog(String file) {
List<File> fileList = new LinkedList<File>();
File myfile = new File(file);
File[] fileNme = myfile.listFiles();
for (File name : fileNme) {
if (name.isDirectory()) {
fileList.add(name);
List<File> fist = sub_Catalogue(name);
Iterator<File> it = fist.iterator();
while (it.hasNext()) {
fileList.add(it.next());
}
} else if (name.isFile()) {
fileList.add(name);
}
}
return fileList;
}
private List<File> sub_Catalogue(File name) {
List<File> fileList2 = new LinkedList<File>();
File[] names = name.listFiles();
Humpty:
if (names == null) {
break Humpty;
} else {
HooHaa:
for (File n : names) {
if (n.isFile()) {
fileList2.add(n);
开发者_如何学Python } else if (n.isDirectory()) {
fileList2.add(n);
List<File> fileList3 = sub_Catalogue(n);
Iterator<File> uf = fileList3.iterator();
while (uf.hasNext()) {
fileList2.add(uf.next());
}
}
}
}
return fileList2;
}
The problem is likely to be that the JTextArea is doing lots of work on each setText/append call. Calling that method a million times will grow the internal string a little bit at a time and do some work. You probably end up with an O(N^2)-like complexity on the size of the list.
Try the following: using a StringBuilder, combine all the strings in the list to form just a single string. Then call setText on the JTextArea using this single big string.
A more efficient way to build the string that you will put as text to the JTextArea is to use a StringBuilder:
List<File> hoohoo = cr.catalog(partition);
Iterator<File> it = hoohoo.iterator();
StringBuilder filesSB = new StringBuilder();
while (it.hasNext()) {
File myf = it.next();
filesSB.append(myf.toString());
filesSB.append("\n");
}
filesText.setText(filesSB.toString());
Here is an article on loading text efficiently in Swing:
http://users.cs.cf.ac.uk/O.F.Rana/jdc/swing-nov7-01.txt
精彩评论