mmgro27
mmgro27

Reputation: 515

Correct caret position after replacing a selection of text in a JTextField

I want the below method to replace a selection of text in a JTextField and replace it with some input String. My problem is that if I select more than a single character in the JTextField, the caret position skips ahead.

How can I ensure that the caret position stays in the correct position?

private void addStringAtCaretPos(String c) {
        final int caretPosition = inputTextField.getCaretPosition();
        inputTextField.replaceSelection(c);

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

    }

Upvotes: 1

Views: 277

Answers (1)

camickr
camickr

Reputation: 324118

I select more than a single character in the JTextField, the caret position skips ahead.

final int caretPosition = inputTextField.getCaretPosition();

Typically when you select text you select from left to right so the caret position is at the end of the text you want to replace.

I would think you should be using:

final int caretPosition = inputTextField.getSelectionStart();

Upvotes: 5

Related Questions