Search code examples
javaswingjtextpanetext-alignmentstringbuffer

Howto align text in JtextPane or StringBuffer


I'm using a JTextPane and wish to align the text result that I received from a StringBuffer. The thread that runs the result returns a String with all the requested result and later, in a different thread, I place the data in a JTextPane.

The code to get the result (String) looks like this:

    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()+"                 ");

Obviously, depends on the length of the state/city the result on screen is inconsistent. Can anyone point out what should be used in order to align it neatly. This can be done either with the StringBuffer or later in the JTextPane.

Thanks

below is a screenshot of the desired result.

enter image description here


Solution

  • Call

    textPane.setContentType("text/html");
    

    and use html table:

    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());