Java – How to move the cursor position in a JTextField

cursorjavajtextfield

I have a JTextField inputTextField and I would like the symbol to be added to the text field at the cursor position when the orButton is pressed. The method below works but after the button is pressed the cursor appears at the end of the field instead of at the position it was before the button is pressed.

How can I set the cursor to move back to its previous position?

private void orButtonActionPerformed(java.awt.event.ActionEvent evt)                                          
    {
        int caretPosition = inputTextField.getCaretPosition();
        String currentText = inputTextField.getText();
        String newText = currentText.substring(0, caretPosition) + 
        "∨" + currentText.substring(caretPosition, currentText.length());

        inputTextField.setText(newText);
        inputTextField.requestFocus();
    }                                        

I thought setCaretPosition() might be what I was looking for but it didn't work.

Best Answer

setCaretPosition() should be the right method. However it seems the caret is set to position 0 again when the text field gets the focus. You could try wrapping it inside a SwingUtilities.invokeLater() call like this:

private void orButtonActionPerformed(java.awt.event.ActionEventevt) {
    final int caretPosition = inputTextField.getCaretPosition();
    String currentText = inputTextField.getText();
    String newText = currentText.substring(0, caretPosition) + 
    "∨" + currentText.substring(caretPosition, currentText.length());

    inputTextField.setText(newText);
    inputTextField.requestFocus();

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            inputTextField.setCaretPosition(caretPosition);
        }
    });
}

Note that you have to declare caretPosition as final for this to work.