Arrows do not move in text field with regex

Asked

Viewed 102 times

2

I have the following code with a regular expression inside a method Keyreleased, which allows only some characters to be typed by the user in a text field:

String text = input.getText();
text = text.replaceAll("[^A-Za-z&\\|!]", "");
input.setText(text.toUpper());

When trying to press arrow keys like <-(left) or (right) ->, regular expression does not let me return to the string to edit something, Regex does not allow.

Example:

inserir a descrição da imagem aqui

The cursor at that moment is in front of C, but I can’t turn the cursor back so it’s in front of B or A.

Would anyone know how to solve this problem?

  • And the code to test?

  • Usually this text.replaceAll is not used to handle pressed key events. Where is the rest of the code?

  • 3

    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.

1 answer

8


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:

inserir a descrição da imagem aqui

In the answer that Linkei there are more details about this class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.