JTextArea: get last line of text

A

Aaron Boxer

Hello,

I have subclassed a JTextArea, and am handling the keyboard events.
I would like to get the last line of text each time the user
presses carriage return. I am going to use the widget as a
serial communication terminal: send each line of text over the serial
port after CR.

Any help would be greatly appreciated.

Aaron Boxer
 
?

=?ISO-8859-1?Q?Daniel_Sj=F6blom?=

Aaron said:
Hello,

I have subclassed a JTextArea, and am handling the keyboard events.
I would like to get the last line of text each time the user
presses carriage return. I am going to use the widget as a
serial communication terminal: send each line of text over the serial
port after CR.

Look up getLineOfOffset and getLineEnd/StartOffset in the documentation.
 
B

Bill Tschumy

Hello,

I have subclassed a JTextArea, and am handling the keyboard events.
I would like to get the last line of text each time the user
presses carriage return. I am going to use the widget as a
serial communication terminal: send each line of text over the serial
port after CR.

Any help would be greatly appreciated.

Aaron Boxer

I haven't compiled this, but this should be pretty close to what you want.

Document document = textArea.getDocument();
Element rootElem = document.getDefaultRootElement();
int numLines = rootElem.getElementCount();
Element lineElem = rootElem.getElement(numLines - 1);
int lineStart = lineElem.getStartOffset();
int lineEnd = lineElem.getEndOffset();
String lineText = document.getText(lineStart, lineEnd - lineStart);
 
A

Aaron Boxer

Hi Bill,

thanks for your reply!

I just had to change one line, because of zero offsets:

Element lineElem = rootElem.getElement(numLines - 2);


Cheers,

Aaron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top