Forums Register Login

How to disable selection in a JTextField?

+Pie Number of slices to send: Send
Hi ranchers,

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 ]
+Pie Number of slices to send: Send
if textfield.setEnabled(false) is not what you're after,
override addMouseMotionListener() to do nothing

simple demo

[ August 16, 2006: Message edited by: Michael Dunn ]
+Pie Number of slices to send: Send
Hi Micheal, thanks for your help.

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?

Thanks!
+Pie Number of slices to send: Send
> Actually I wanna prevent any operation which can select part of or the whole text.

what is the purpose of this?

if it is to prevent copying, override copy(), to do nothing.
+Pie Number of slices to send: Send
Hi Micheal,

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.

Any hints?

Thanks
+Pie Number of slices to send: Send
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.
Quick! Before anybody notices! Cover it up with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 6405 times.
Similar Threads
JTextField
Tab Order
automatic scrolling of JTextField
System Date
Trying to convert jtextfields to a double
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 22:43:20.