Java help needed

toh6wy

Emperor
Joined
Aug 20, 2003
Messages
1,403
Location
Omnipresent
I wouldn't be surprised if this is really basic, but... I'm trying to create a text editor. Right now, when I load a file (one line at a time, using BufferedReader's readLine and then TextArea's append), it always scrolls as it appends. Although I use TextArea's setCaretPosition to make it go back to the top, you can still quite easily see it very quickly scroll to the bottom before jumping to the top when you open a file. How do I prevent this, and make it act like a normal text editor??
 
It probably depends what else you want to be able to do with the TextArea, but you could read the file into a string object, then create the TextArea using

new TextArea (your_string, rows, columns);
 
Perhaps this could help:


try {
File file = new File("c:/text.txt");
BufferedReader br = new BufferedReader(new FileReader(file));

StringBuilder sb = new StringBuilder(); // or StringBuffer in older Javas
String record;

while ( (record = br.readLine()) != null) {
sb.append(record + '\n');
}

textArea.setText(sb.toString());
textArea.setCaretPosition(0);
}
catch (IOException exc) {}


If you use string += record; , it can take ages to load larger files.
 
Yes! After using a variant of Ragazzo's idea, I got it to work, finally. Thank you very much! :)
 
Back
Top Bottom