KeyListener receives the "key-hit" before my JTextField does..?
I got a JTextField
, and to that field I have added a Keylistener
. Inside the keyPressed
method, I ask the method to print (System.out.println
) whats inside the JTextField
.. If I hit a letter, it seems as the Keylistener
receives this key-hit before the JTextField
is updated.. I have to hit two letters to see the first one..
All I need to do is to make every let开发者_C百科ter upper-case as they are inputted.. This I am trying to do by listening to every key (I also listen to the ENTER key for other reasons) and then do a textfield.setText(textfield.getText().toUpperCase());
Use a DocumentFilter to alter the text as it comes in.
Not the prettiest source and it's not 100% correct, just showing how it works. See the 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);
}
}
I know its not so popular to answer your own question.. but I guess I found the solution.. Instead of doing all the upper-casing in the keyPressed method, I do it in the keyReleased :)
Try using the underlying document:
textfield.getDocument().addDocumentListener(yourListener);
精彩评论