0

This is the exact alignment from the text file

When I append the data to the JTextArea in Java it does not copy the alignment.

This is the image of the text area and the alignment is very different from the txt file.

1 Answer 1

2

There could be 2 problems at hand. If your original textfile is using Tabs instead of spaces to align its columns the way it does, you need to set the same tab size on your JTextArea component.

See JavaDoc for setTabSize(int)

Secondly, alignment can only really be achieved with a mono-sapced font (where every character has the same visual width).

See JavaDoc for setFont(Font)

I just found this answer by Guillaume Polet where he describes the way to get a general-purpose monospace font by simply specifying monospaced as the font's name:

JTextArea textArea = new JTextArea(24, 80);
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
8
  • I am currently using this format to write data to txt file
    – Newbee
    Commented Nov 24, 2021 at 16:38
  • String format = "%-15s %-15s %-15s";
    – Newbee
    Commented Nov 24, 2021 at 16:38
  • it goes exactly to text file but when retrieve again and put to jtextarea the alignment is not correct.
    – Newbee
    Commented Nov 24, 2021 at 16:39
  • So you enter the text in a JTextArea, save it to a .txt file by using the above formatting String and then you load it back into the JTextArea but with the worng alignment? Commented Nov 24, 2021 at 16:43
  • No i put some data to the txt file first then i retrieve them again via jtextarea.
    – Newbee
    Commented Nov 24, 2021 at 16:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.