这是我的代码:
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);
我应该怎样做才能使文本正确对齐,而不管文字的长度如何?
我想尽可能地使用JTextArea而不是JTable(因为我还不熟悉它) 先谢谢你了!
答案 0 :(得分:2)
使用JTextPane
代替JTextArea
,因为可以执行 HTML 。然后添加HTML <table>
。可能有一些风格。
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());
这允许比例字体和样式文本,如粗体,红色,背景颜色。
答案 1 :(得分:1)
正如@AndyTurner所提到的,最好的方法是依靠String格式化程序来设置要打印的每个变量的字符宽度,同时还要具有右对齐或左对齐的能力。所以在你的情况下,当你向左对齐时,它可能是这样的:
txtArea.setText(String.format("%-3s%-20s%-5s%-5s%n", num, name, stocks, req));
在此示例中,我为3
分配了num
个字符,为20
分配了name
个字符,为5
和stocks
分配了req
个字符
更多详情here
答案 2 :(得分:1)
我想使用JTextArea而不是JTable(因为我还不熟悉它)
好吧,现在是时候熟悉JTable了。为作业使用适当的组件,这就是存在多个组件的原因。不要试图将方形钉固定在圆孔中。
JTextArea不是这种格式的适当组件。
相反,您应该使用mystring
。 JTable
旨在以行/列格式显示数据。有关更多信息和工作示例,请查看How to Use Tables上Swing教程中的部分。
如果必须使用文本组件,请使用JTextPane。您可以手动设置选项卡的值,以便对齐所有文本。此方法的问题是您还需要确定每个选项卡的大小。因此,这意味着要么随机猜测每列的大小,要么迭代所有数据以确定大小。当然这会使代码复杂化。有关示例,请参阅:Java Setting Indent Size on JTextPane。
同样,更好的解决方案是学习使用Swing如何设计使用它。
答案 3 :(得分:0)
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);