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;
– user28595
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).
– Daniel Santos
This code snippet is not a [mcve]. It needs more context that has not been provided.
– user28595
See if you’re better now
– Daniel Santos