araraujo
araraujo

Reputation: 633

Java Swing - How to position cursor inside JTextField from PlainDocument

My java swing application has a JTextFied. I am usind a PlainDocument subclass for input manipulation.

public class MaskDecimalDocument extends PlainDocument {

   public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

      //manipulation input code

      super.insertString(0, manipulatedText, a);

   }

}

The user insert a character, the insertString method handle the haracter and inserts it in the text. Next manipulation, the cursor is positioned at the end of text. How do I position the cursor at original place ?

Upvotes: 0

Views: 340

Answers (2)

VGR
VGR

Reputation: 44338

Controlling the caret position is not a Document’s job. You should set a NavigationFilter which ignores all changes to the caret position:

textField.setNavigationFilter(new NavigationFilter() {
    @Override
    public void setDot(FilterBypass bypass,
                       int position,
                       Position.Bias bias) {
        // Deliberately empty
    }

    @Override
    public void moveDot(FilterBypass bypass,
                        int position,
                        Position.Bias bias) {
        // Deliberately empty
    }

    @Override
    public int getNextVisualPositionFrom(JTextComponent component,
                                         int position,
                                         Position.Bias bias,
                                         int direction,
                                         Position.Bias[] newBias) {
        return position;
    }
});

Upvotes: 1

camickr
camickr

Reputation: 324118

You may want to consider using a DocumentFilter since it is the newer API for handling changes to a Document. The concept is the same but the class is more reusable since it can be added to any Document.

Read the section from the Swing tutorial on Implementing a DocumentFilter for more information.

How do I position the cursor at original place ?

When you create your custom DocumentFilter class you would need to pass in the text field that uses the Document as a parameter and save this text field as an instance variable of your class.

Then the logic in the replaceSelection(...) method would be something like:

int caretPosition = textField.getCaretPosition();
super.replaceSelection(...);
textField.setCaretPosition( caretPosition );

Note you may need to place the setCaretPosition(...) method in a SwingUtilities.invokeLater() to make sure the code is executed after the default processing for setting the caret position.

Upvotes: 1

Related Questions