I have a JTextField in which I wanna prevent the user from selecting text. How do I achieve this? Thanks! [ August 16, 2006: Message edited by: Can Zheng ]
Well I guess I've made a mistake by adding "by mouse" in the previous post. Actually I wanna prevent any operation which can select part of or the whole text. By not adding a motion listener we prevent mouse to do it but still we can use shift and arrow key to select it. Is there any other way to do it?
I have this JTextfield which accepts only 6-character ID, so I preset it with something like 000000, and then treat every input as a replace(i.e overwrite the character at the caret position). I did all the above by overiding the insertstring in the textfield's document class. The problem is when the user can select some text, he can delete it or directly type something to replace the selected part. I know I can override delete() in the document class to prevent that, but with selection enabled but deleting and overwriting disabled is quite unintuitive to me. So I'd like to disable selection as well.
don't know that there's a non-ugly way to do this. A keylistener checking isShiftDown() and resetting selectionStart/end to the caret position seems to work OK, but the code sure is ugly.
if you're already using a document to replace/insert a single character, perhaps it might be easier to allow the multi-character selection, then check if(textfield.getSelectedText().length() == 1) (check for null first) or, if using a DocumentFilter, the length argument, then proceeding if true.
Post by:autobot
Quick! Before anybody notices! Cover it up with this tiny ad:
a bit of art, as a gift, the permaculture playing cards