how to position a Jtextfield’s Caret?

Asked

Viewed 217 times

0

I have a JTextField where opening and closing of parentheses is optional. However, whenever the user opens and does not close a parenthesis, my program gives error, because I use this text field to calculate an arithmetic expression.

In order to avoid this error, I would like to, as soon as the user type the "(" I would complete with the ")" and put Caret between those characters, but I don’t know how to do it. For example:

JTextField txt = new JTextField;
txt.setText("2*(");
String ultimoCaractereDigitado = txt.substring (txt.length() - 1, txt.length());

if(ultimoCaractereDigitado.equals("(")){
    txt.setText(ultimoCaractereDigitado+")");
    //text.getText() = 2*()
    txt.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent caret) {
        //Posição do caret: penúltimo caractere, ou seja, entre o "(" e ")"    
        caret.setDot(txt.getText().length - 2);
        }
    });
}

The method ce.setDot() there is no, there is some way I can set the position of the Caret other than by caretUpdate ?

  • Please provide a [mcve] so that it is possible to simulate the problem and propose a solution;

  • I believe it is not related, because I do not want to set the position of the Caret when the text field gets focus, but when I type a certain character ("(" in the case).

  • This code snippet is not a [mcve]. It needs more context that has not been provided.

  • See if you’re better now

1 answer

1


You can do it by mixing the PlainDocument and CaretListener, where with the first class you detect if what was typed in the field is the opening of the parenthesis and concatenates the closure together, and with the second, you position the cursor between both. For this, I used a boolean variable hasOpenParentese so that both methods have a way of "communicating" and pro CaretListener know when to reposition the cursor:

textField.setDocument(new PlainDocument() {

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if (str.equals("(")) {
            hasOpenParentese = true;
            str += ")";
        }
        super.insertString(offset, str, attr);
    }
});

textField.addCaretListener(e -> {
    if (hasOpenParentese) {
        hasOpenParentese = false;
        JTextComponent comp = (JTextComponent) e.getSource();
        comp.setCaretPosition(e.getDot() - 1);
    }
});

Resulting:

inserir a descrição da imagem aqui

I made an executable example on github, if you want to test before applying in your code.

Browser other questions tagged

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