user3437460
user3437460

Reputation: 17454

Get last input character in a JTextArea

I wanted constantly keep track of what is entered in a JTextArea, thus I want to get the last input character in a JTextArea everytime the user type something.

I am able to come out with the entire working program. However the way I get the last input character is this:

textArea.getText().charAt(textArea.getText().length()-1);

This way, I always have to get the entire string of text from JTextArea first.

My question is: Is there anyway better way to allow me to get the last input character without getting the entire text from the JTextArea first?

Upvotes: 0

Views: 1693

Answers (2)

acearch
acearch

Reputation: 342

How about using a DocumentListener? http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#doclisteners Underlying object for a JTextArea is a Document. So you could trap the required update event obtain the last input character and store it in a variable. Assuming this is what you are looking for.

Upvotes: 1

isnot2bad
isnot2bad

Reputation: 24444

You can query an arbitrary part of a JTextArea:

Document doc = textArea.getDocument();
String lastCharAsString = doc.getText(doc.getLength() - 1, 1);

If you even care about creating a one-character-String every time, this might be another solution which does not even create a String instance:

Segment seg = new Segment(); // can be reused
Document doc = textArea.getDocument();
doc.getText(doc.getLength() - 1, 1, seg);
char last = seg.last(); // equal to seg.first()

Upvotes: 2

Related Questions