Differentiate between typing and pasting in JTextField

53 views Asked by At

i've been looking around and haven't been able to find any solution to this problem: i have a JTextField and i want to do some things when the user paste something in there, i've found this: What event to use when pasting something in a JTextField?

which works ok, except that i want only to do things when the user paste something, not when it writes on the text field, i've though of saving the previous value of it and compare it with the new, and if it was empty and now is not, do things, but this won't work since it will enter in that condition when the user types the first letter in the text field.

If anyone knows how to do it whit the documentListener or whit any other listener it would be of grate help.

Update: since various people has asked, the reason i want to do this is because the text will come from a bar code reader or some similar device.

2

There are 2 answers

1
camickr On

except that i want only to do things when the user paste something

Why should pasted text be treated any different than typed text? Sounds like a design issue. If you specify a better reason/requirement for doiong this we might be able to come up with a better solution.

i want to do some things when the user paste something in there

You might be able to override the paste() method of the JTextField. Just override the method to invoke super.paste() and then add your custom code.

how to do it whit the documentListener

Maybe you would consider a "paste" to mean more than one character is added at a time. In which case you just test the length of the String that is added to the Document.

0
Kevin Chacón On

I was able to fix my problem by configuring my bar code scanner and making it send a "new line" after each reading, and executing my code every time this happens with the actionPerformed of the JTextField. Thanks to everybody who tried to help.