Getting the visible lines from a JTextArea
I'm using aJTextArea with a fixed size. I've used thesetLineWrap(true) andsetWrapStyleWord(true) methods on thisJTextArea, so when the user types in some text longer than the visible width, it will wrap into the next line. I need to get each visible line from theJTextArea to create a String array of text lines.
I mean visible text lines (lines visibly separated in theJTextArea), not real text lines separated by a line break character as "\n".
How can I do this?
[534 byte] By [
rexkravena] at [2007-11-26 22:48:47]

# 2
This information is supposed to be contained in the View information of the component. But as far as I can tell it doesn't work for a JTextArea.
So if you can use a JTextPane then check out the "getWrappedLines" method in this posting:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
Basically, a View exists for each line in the Document and then each line may have multiple views if the line needs to wrap. So the basic code just count the number of views within each line but you can change the code to get each view separately. Once you have each view you can get the start and end of the text from the document that this View represents.
Or if you need to use a JTextArea then you can calculate the starting offset of each each line with respect to the model. You can use the viewToModel(..) method to get the starting offset of each line. We know that each line in a text area is a fixed height, so the starting offset of the first line would be modelToView(0, 0); If the line height is 16, then the starting offset of the second line would be modelToView(0, 16), etc. Once you know the starting offset of each line you can subString out the text for each line.
# 3
Well, this is the code I've finally used:
public ArrayList<String> getWrappedLines(JTextArea myTextArea) {
ArrayList<String> linesList = new ArrayList<String>();
int length = myTextArea.getDocument().getLength();
int offset = 0;
try {
while (offset < length) {
int end = Utilities.getRowEnd(myTextArea, offset);
if (end < 0)
break;
// Include the last character on the line
end = Math.min(end+1, length);
String line = myTextArea.getDocument().getText(offset, end - offset);
// Remove the line break character
if (line.endsWith("\n"))
line = line.substring(0, line.length() - 1);
linesList.add(line);
offset = end;
}
} catch (BadLocationException e) { }
return linesList;
}
PD: It doesn't return a String array but an ArrayList of Strings