Jump to content

Automatic new line in TextArea, possible?

- - - - -

  • Please log in to reply
5 replies to this topic

#1
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
Is possible to make TextArea change line when reach a number of characters?
Thank you

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Of course. The only limits are the APIs and your immagination =)

#3
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
Oookk...how then? =P

#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
you could keep track of the number of characters after the last '\n'. When the maximum is reached, append a "\n" to the textarea and reset the number to 0.

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
First, add a keyListener to your jtextarea.
Now, you could do textArea.getText() count the amount of caracters after the last \n and you know the amount of caracters on that line. If it reached the limit, add \n.

String text = textArea.getText();


But..
Users can type something and then use the arrow keys or mouse to move the cursor back up, and this won't work anymore. You will need to know at which line the user is currently typing.
To get this kind of info you need the caret. (caret = the blinking cursor thing)

Caret caret = textArea.getCaret();

The caret has the following method:

Quote

getMark

public int getMark()
Fetches the current position of the mark. If there is a selection, the mark will not be the same as the dot.
Returns:
the position >= 0

This is the index of the cursor relative to the whole text.
So if the text has 3 lines of 30 characters, and you put the cursor at the first position on line 2. The getMark will return 31(\n is also counted as character, \n is also in the String of textArea.getText, so that's a good thing)

You'll end up with code like:

int position = caret.getMark();

String beforeCaret = text.subString(0, position);

int lastEnter = beforeCaret.indexOf("\n");

if( (beforeCaret.length()-lastEnter) > limit){

   //Add enter here.

} 

...Oorrrr something like that. I just put this together, didn't test it or anything.
Good luck.

(you'll need to watch out for the first line, it won't contain a \n, and the indexOf returns -1.
beforeCareth.length() - -1 will result in a bigger number than it should be, and with the current if-statement the first line will be cut off too soon.
(Easy fix is to just add a \n at the front in the beforeCaret String))

#6
toto_7

toto_7

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 295 posts
WoW thanks a lot




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users