Search code examples
javaswingfile-iojtextarea

How to keep same layout of .txt file when importing it into JTextArea in a Java application?


I have an app where I read from .txt file and than write from it into the JTextArea. But the problem is that the layout is not consistent (as seen on this picture:

https://i.sstatic.net/CaUmN.png

I think that text area doesn't recognize tabulators. Can someone help me how to get the same layout in the text area as it is in .txt file?


Solution

  • No, the difference is that the font on the left is monospace, and the default Java font is not. Apply a monospaced font to the text area using setFont. A common monospace font Courier/Courier New, but may not be available on your machine. Instead, request a monospaced font and Java should handle it for you.

    textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));