Reputation:
Here is a picture of my JTextArea:
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!
Upvotes: 3
Views: 2426
Reputation: 324207
I want to use JTextArea not JTable (since I'm not familiar with it yet)
Well, now is the time to become familiar with a JTable. Use the proper component for the job, that is why multiple components exist. Don't try to fit a square peg in a round hole.
A JTextArea is not the appropriate component for that kind of formatting.
Instead you should be using a JTable
. A JTable
is designed to display data in a row/column format. Check out the section from the Swing tutorial on How to Use Tables for more information and working examples.
If you must use a text component then use a JTextPane. You can manually set the value of a tab so all the text is aligned. The problem with this approach is again you need to determine what the size of each tab should be. So this means either you make a random guess at the size of each column or you iterate through all the data to determine the size. Of course this complicates the code. See: Java Setting Indent Size on JTextPane for an example.
Again, the better solution is to learn to use Swing how it was designed to be used.
Upvotes: 1
Reputation: 109613
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.
Upvotes: 2
Reputation: 45005
As mentioned by @AndyTurner above your best approach is to rely on the String formatter to set the character width of each variable to print with also the ability to right or left justified. So in your case, as you left justified everything it could be something like that:
txtArea.setText(String.format("%-3s%-20s%-5s%-5s%n", num, name, stocks, req));
In this example I allocated 3
characters for num
, 20
for name
and 5
for stocks
and req
.
More details here
Upvotes: 1
Reputation:
String display = "";
// just add values accordingly the best way to get the result you
// want is to mess around with formatting until you have the values
// where you want them in the textfield.
display = String.format("%20s %10s%n", value1, value2);
//display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
// stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);
Upvotes: 0