StephenKhoa StephenKhoa - 1 month ago 16
Java Question

JTextArea, JTextField, how to replace text from the caret to the left with another string

I'm making a text processing program, and I want if the user press 'a' ('a' is just for demonstration, I have a list of special characters like that), it will replace some characters from the caret to the left with a string.

I have tried "setText" method but it replaced then moved the caret and the text component scrolled to the end, what I want is the caret not to move anywhere else and the text component not to scroll to the end, how can I code to do that(I am overriding the processKeyEvent)?

Any help would be appreciated.

Answer Source

Try to use document filter:

    JTextArea textArea = new JTextArea();

    ((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {            
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {

            if ("a".equals(text)) {
                text = "B";

            super.replace(fb, offset, length, text, attrs);