As I mentioned in the comments but it never hurts to repeat, the problem has nothing to do with the replaceAll
or with the regex, and yes with the Reader you are using.
The event KeyReleased
is fired every time a key is released after being pressed. Arrows are also keys, so every time you press any, the event will be fired.
Since you did not provide a relevant excerpt for analysis, I will assume that your event is similar to below:
@Override
public void keyReleased(KeyEvent e) {
JTextComponent input = ((JTextComponent) e.getSource());
String text = input.getText();
text = text.replaceAll("[^A-Za-z&\\|!]", "");
input.setText(text.toUpperCase());
}
Note that each time a key is pressed in the text box, this whole routine will occur. And when you press a direction key (or arrows), the entire text of the field will be filtered by regex and then reapplied into the field, and this will cause the Caret
pattern(that text cursor that appears in the field),moves to the end of the new sentence applied.
It is not recommended to use keyboard events to filter strings in text fields, since text fields have another appropriate means for this, which is through the classes derived from Document
.
In this answer there is an example of class use PlainDocument
, adapting to your situation, it would be something like below:
input.setDocument(new PlainDocument() {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str == null) {
return;
}
super.insertString(offs, str.replaceAll("[^A-Za-z&\\|!]", "").toUpperCase(), a);
}
});
Working:
In the answer that Linkei there are more details about this class.
And the code to test?
– user28595
Usually this
text.replaceAll
is not used to handle pressed key events. Where is the rest of the code?– Jefferson Quesado
I applied that same query here and did not give the problem. If you do not provide one [mcve] It gets tricky to help you. I repeat: the problem has nothing to do with replaceAll or regex, is another piece of code you’re not reporting.
– user28595