• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to disable selection in a JTextField?  RSS feed

 
Can Zheng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Can Zheng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> 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.
 
Can Zheng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!