How to format text in JText Area?

504 views Asked by At

I have a scrollable JTextArea that displays output from an ArrayList of Objects. After each element is appended to a line, it goes to the next line to append the information from the next element. However, my output looks unorganized. I would like for each attribute to line up with eachother regardless of the length of each element. I tried using loops to create an even number of spaces between each attribute but they still do not line up correctly.

Here is the function that appends the Strings from the Objects to the JTextArea

public static void appendOutputForTextArea(List<Book> catalog) {
    String output = ""; 
    mainFrame.displayArea.setText("");
    int titleCol = 50; 
    int authorCol = 50; 
    int isbnCol = 50;  
    for(int i=0; i < catalog.size(); i++) {
        output += catalog.get(i).getTitle(); 
        for(int k=catalog.get(i).getTitle().length(); k < titleCol; k++) {
            output += " ";  // create enough whitespace before next element
        } 
        output += catalog.get(i).getAuthor();    
        for(int k=catalog.get(i).getAuthor().length(); k < authorCol; k++) {
            output += " ";
        } 
        output += catalog.get(i).getIsbn(); 
        
        for(int k=catalog.get(i).getIsbn().length(); k < isbnCol; k++) {
            output += " ";  
        } 
        
        output += catalog.get(i).getQuantity(); 
        output += "\n";  
        
    }
    mainFrame.displayArea.append(output);
}

Here is what the text area looks like.

Output Screen

1

There are 1 answers

2
DUDSS On

Note that JTextArea supports tab stops. Meaning that you can format text into a sort of a makeshift table by inserting a tab (character \t) after the text to fill the remaining space to the text areas' tab size, forming a table cell.

The tab size can also be changed by using the textArea.setTabSize​(int size) method. I think this doesn't even require a monospaced font.

In your case the code would look something like

output += catalog.get(i).getTitle() + "\t";

and so on.

Using a JTable might be preferable though.