Search code examples
javaswingnewlinejtextfield

final character '\n' at the end of my string has been modified to space character


I was hoping to retrieve the newline character at the end of the text in a JTextField, however after setting the text field's text to my string, it has been modified to be a space character. The code below highlights the problem.

Is it possible to preserve the \n in the text field?

import javax.swing.JTextField;

public class StackOver {
    public static void main(String[] args) {
        String hasNewLineEscapeCharacter = makeStringWithNewLineCharacter();
        JTextField backgroundText = new JTextField(90);
        backgroundText.setText(hasNewLineEscapeCharacter);
        char spaceChar = backgroundText.getText().charAt(backgroundText.getText().length()-1);
        char newLineChar = hasNewLineEscapeCharacter.charAt(needsNewLineEscapeCharacter.length()-1);
    }

    public static String makeStringWithNewLineCharacter() {
        String str = "hello,world!";
        str += ('\n');
        return str;
    }       
}

Solution

  • Is it possible to preserve the '\n' in my JTextField?

    A JTextField uses a PlainDocument which contains a property that filters the "\n" and replaces it with a space character.

    To preserve the newline character in the text field you can try:

    textField.getDocument().putProperty("filterNewlines", Boolean.FALSE);
    

    However, this will cause the text to display on two lines just like a text area.

    So as suggested above you should just be using a JTextArea.

    There is no way to display text that contains a newline character on a single line.

    What you might want to do is store some other unprintable character in the text string and then use a String.replaceAll(...) if you ever need to access the text with the newline character added back in.