Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA How to align text in JTextArea regardless of length of characters

Tags:

java

swing

Here is a picture of my JTextArea: enter image description here

Here is my code:

String display = "";
display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
        stocks + "\t\t\t" + req +"\n";

txtArea.setText(display);

What should I do so that the texts are aligned properly regardless of the length of characters of the words?

As much as possible I want to use JTextArea not JTable (since I'm not familiar with it yet) Thank you in advanced!


1 Answers

Use a JTextPane instead of JTextArea, as that can do HTML. Then add an HTML <table>. Probably with some styles.

StringBuilder display = new StringBuilder("<html><table>");

display.append("<tr><td align='right'>").append(num)
        .append("</td><td>").append(name)
        .append("</td><td align='right'>").append(stocks)
        .append("</td><td>").append(req)
        .append("</td></tr>");

display.append("</table>");
txtPane.setText(display.toString());

This allows proportional fonts and styled text like bold, red, background colors.

like image 147
Joop Eggen Avatar answered Jan 23 '26 21:01

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!