Question

I'm writing a DocumentFilter which replaces all of the word "top" entered into a JTextField with the logical top symbol.

Using this code is fine, however it's annoying as the user has to re-type their space, which they can do and the text continues on the same line

temp.replaceAll("\\btop\\b", "\\\u22A4" );

using this code and adding in the space with the replacement causes the top symbol and all the text in the JTextField to be pushed up slightly when the user continues typing the text then goes underneath and starts a new line

temp.replaceAll("\\btop\\b", "\\\u22A4 " );

Can anyone please explain this behaviour and hopefully provide a solution? Thank you.

 @Override
    public void replace(FilterBypass fb, int offset, int length,
        String string, AttributeSet attr)
            throws BadLocationException {
        int totalLength = fb.getDocument().getLength();
        String temp   = fb.getDocument().getText(0, totalLength);
        temp = temp.replaceAll("\\btop\\b",     "\\\u22A4" );  //needs space            
        super.remove(fb, 0, totalLength);
        super.insertString(fb, 0, temp, attr);
        super.replace(fb, offset, length, string, attr);
}
Was it helpful?

Solution

I think this is likely caused by your replacing a non-space word boundary (such as a newline or carriage return) with a simple space. So the flow of the text is being altered.

Seeing as the \\b anchor relies on the \\w character class, you could instead match and capture the \\W non-word characters either side of "top" and then reinsert them into the result:

temp = temp.replaceAll("(\\W)top(\\W)", "$1\\\u22A4$2" );

That way you will capture spaces or newlines, carriage returns, tabs, etc, and restore them either side of the "top" substitute, so that the document remains exactly the same except that "top" has become "⊤".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top