KeyListener gets "key-hit" before my JTextField does ...?

I have a JTextField , and I added a Keylistener to this field. Inside the keyPressed method, I will ask the print method ( System.out.println ), which is inside the JTextField . If I press a letter, it seems that the Keylistener gets this hit key before the JTextField updated .. I need to click two letters to see the first one.

All I have to do is make each letter uppercase as I type. I try to do this by listening to each key (I also listen to the ENTER key for other reasons), and then do textfield.setText(textfield.getText().toUpperCase());

+4
source share
3 answers

I know that it is not so popular as to answer your own question .. but I think I found a solution. Instead of doing all the tops in the keyPressed method, I do it in keyReleased :)

+2
source

Use DocumentFilter to change the text as it appears.

Not the most beautiful source, and it is not 100% correct, just showing how it works. See original here

 ((AbstractDocument)textField.getDocument()).setDocumentFilter(new UppercaseDocumentFilter()); class UppercaseDocumentFilter extends DocumentFilter { public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { fb.insertString(offset, text.toUpperCase(), attr); } public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { fb.replace(offset, length, text.toUpperCase(), attrs); } } 
+4
source

Try using the base document:

 textfield.getDocument().addDocumentListener(yourListener); 
0
source

Source: https://habr.com/ru/post/1299959/


All Articles