skibum
skibum

Reputation: 11

Formatting in a JTextfield

When I do this:-

GUI.this.libraryResult.setText(String.format("%-30s%-30s%-20s%-20s%n","\tTITLE","AUTHOR","YEAR","ISBN"));
for (Book book : booklist) {
    GUI.this.libraryResult.setText(libraryResult.getText() + String.format ("%-30s%-30s%-20s%-20s%n",
            "\t" + book.getTitle(), book.getAuthor(), book.getYear(), book.getISBN()));

I get this:

What am I doing wrong that is stopping them justifying left properly?

Upvotes: 1

Views: 170

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

The problem is that the text area is using a variable width font (where an I will take up less width than a W). Use a Font.MONOSPACED to fix the immediate problem.

More generally though, this is tabular data. A JTable was designed for just this purpose! More importantly, it offers many handy features, like the ability to sort or filter the table, or use different formatting for different columns (e.g. making the Title/Author italic) and values in a column (e.g. giving the Year a darker color by decade).

Upvotes: 1

Related Questions