So I want to automatically convert all entered characters to uppercase.
Here is relevant part of the code :
editorPane = new JEditorPane();
editorPane.getCaret().setBlinkRate(0);
this.keyListener = new UIKeyListener(editorPane);
editorPane.addKeyListener(keyListener);
And the UIKeyListener Class I am only providing the keyReleased function as other part is just boilerplate code
@Override
public void keyReleased(KeyEvent e) {
capitalizeCode();
}
private void capitalize() {
int prevCarerPosition = editorPane.getCaretPosition();
editorPane.setText(editorPane.getText().toUpperCase());
editorPane.setCaretPosition(prevCarerPosition);
}
This is mostly OK but the problems are :-
- I cannot select text
- Every time I type the characters they first appear in small letters then become capital
Now The first problem is solved if I call the capitalize function from keyTyped function but there there is a new problem : the last typed letter remains small
And I also want to ask whether can we do this without listening to keyevents like by default the editorpane will only accept capital letters?
Don't use a KeyListener.
A better approach is to use a
DocumentFilter.This will work whether text is typed or pasted into the text component.
The filter can be used on any text component.
See the section from the Swing tutorial on Implementing a DocumentFilter for more information.