Java 如何对齐JtextPane或StringBuffer中的文本

Java 如何对齐JtextPane或StringBuffer中的文本,java,swing,jtextpane,text-alignment,stringbuffer,Java,Swing,Jtextpane,Text Alignment,Stringbuffer,我正在使用JTextPane,希望对齐从StringBuffer接收到的文本结果。运行结果的线程返回一个包含所有请求结果的字符串,稍后,在另一个线程中,我将数据放在JTextPane中 获取结果(字符串)的代码如下所示: info.append("\n\nResult:\n"); for (TResult result : results) info.append(result.getID()); info.append("\n"); for

我正在使用JTextPane,希望对齐从StringBuffer接收到的文本结果。运行结果的线程返回一个包含所有请求结果的字符串,稍后,在另一个线程中,我将数据放在JTextPane中

获取结果(字符串)的代码如下所示:

    info.append("\n\nResult:\n");

    for (TResult result : results)
        info.append(result.getID());

    info.append("\n");

    for (TResult result : results)
        info.append(result.getApprovalDateStr+"              "); //the space is used for the alignment 

    info.append("\n");

    for (TResult result : results)
        info.append(result.getState+","+result.getCity()+"                 ");
显然,取决于州/市的长度,屏幕上的结果不一致。有人能指出应该使用什么来整齐地对齐它吗。这可以使用StringBuffer完成,也可以稍后在JTextPane中完成

谢谢

下面是所需结果的屏幕截图


定义辅助函数:

private void log(StringBuilder buffer, String data, int numberOfSpaces) {
    buffer.append(String.format("%" + numberOfSpaces + "s", data));
}
然后:


定义辅助函数:

private void log(StringBuilder buffer, String data, int numberOfSpaces) {
    buffer.append(String.format("%" + numberOfSpaces + "s", data));
}
然后:

召唤

并使用html表格:

info.append("<html><table>");

for (TResult result : results)
    info.append("<tr><td>"+result.getID()+"</td><td>"+result.getApprovalDateStr+"</td><td>"+result.getState+","+result.getCity()+"</td></tr>");

info.append("</table></html>");

//then
textPane.setText(info.toString());
info.append(“”);
for(TResult结果:结果)
info.append(“+result.getID()+”+result.getApprovalDateStr+“+result.getState+”,“+result.getCity()+”);
信息。附加(“”);
//然后
textPane.setText(info.toString());
呼叫

并使用html表格:

info.append("<html><table>");

for (TResult result : results)
    info.append("<tr><td>"+result.getID()+"</td><td>"+result.getApprovalDateStr+"</td><td>"+result.getState+","+result.getCity()+"</td></tr>");

info.append("</table></html>");

//then
textPane.setText(info.toString());
info.append(“”);
for(TResult结果:结果)
info.append(“+result.getID()+”+result.getApprovalDateStr+“+result.getState+”,“+result.getCity()+”);
信息。附加(“”);
//然后
textPane.setText(info.toString());

这与此无关,但我更喜欢
SteingBuilder
而不是
StringBuffer
JTextPane
将支持RTF和HTML等格式化文档。您可以将其格式化为HTML表。这不相关,但我更喜欢
SteingBuilder
而不是
StringBuffer
JTextPane
将支持RTF和HTML等格式化文档。您可以将其格式化为HTML表。是的,这确实起到了作用,但我决定使用Elias解决方案,因为它在将来的维护中提供了更大的灵活性+1.谢谢是的,这确实奏效了,但我决定使用Elias解决方案,因为它在将来的维护中提供了更多的灵活性+1.谢谢