Reputation: 633
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
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
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