Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

controlling caret position in a textfield

Status
Not open for further replies.

casper84mel

Programmer
Oct 21, 2006
3
TR
Hi there;

I have a text field in which I want to be able to have control over the caret of the text field. e.g. when a left arrow key is pressed I want to be able to move the caret of the textfield to any position I want, rather to the next position in the field.
For example, a text field below, the caret is at the beginning of the field;
------------------------
|java-forum
------------------------
a press of left arrow key would normally set the positon after character 'j', before the character 'a'. But I want to make it move to the position just before the character 'f', so I want the text field to look like;
------------------------
java-|forum
------------------------
For this reason I extended the JTextField and implemented the KeyListener interface, and used the setCaretPosition method at the 'keyPressed' to set the caret to the position I want. But it seems that it moves the character to one more position, that it moves the caret to the position just after the character 'f'. The field looks like below;

------------------------
java-f|orum
------------------------
So does anybody know why this happens? I have searched for it and found out that the problem may be related about the defaultcaret behaviour, but I couldn't figure it out :(
Any help,idea,code piece will be greatly appreciated..

Thanks a lot
Cheers
 
It's quite possible that setCaretPosition is 0 based, not 1 based. To put it at the beginning of the row, pass it 0. To put it between the 4th and 5th characters, pass it 4. Think of it as "setCaretPositionAfter"!

 
Actually I dont set my caret according to a fixed integer, that is to set my caret I use a relative position, here I use the '-' as the reference point. I tried to solve the problem via writing a NavigationFilter and so by writing my own setDot function, not using the default one.
Thanks a lot for the comments.
Cheers :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top