I have JTextField
where opening and closing 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, as soon as the user types in "("
I would complete with ")"
and put the caret between those characters, but I do not 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 ce.setDot()
method does not exist, is there any way I can get the position of the caret other than caretUpdate
?