I am trying to create an array of Strings to use with JList, I have a array of objects from my Book class which contains the Author name, Tittle etc... But when I use string.format and send it to my JList the text doesn't come out aligned like when I use system.out.format.
Code:
final static String FORMAT = "|%1$-25s|%2$-25s|$%3$-10.2f|%4$-15s|%5$-13s|\n";
static String[] createStringList(Book[] dataBase)
{
String[] list = new String[dataBase.length];
for (int i = 0; i < dataBase.length; i++)
{
list[i] = String.format(FORMAT, dataBase[i].getTittle(), dataBase[i].getAuthor(),
dataBase[i].getBookPrice(), dataBase[i].getNumberInStock(),
dataBase[i].getISBNNumber());
}
return list;
}
static void printout(Book[] dataBase)
{
System.out.println(" Tittle" + "\t" + " Author" + "\t" + " Price" + "\t" + "Number In Stock" + "\t" + " ISBN Number");
System.out.println("_____________________________________________________________________________________________");
for (int i = 0; i < dataBase.length; i++)
{
System.out.format(FORMAT, dataBase[i].getTittle(), dataBase[i].getAuthor(),
dataBase[i].getBookPrice(), dataBase[i].getNumberInStock(),
dataBase[i].getISBNNumber());
}
}
Result Screenshot:
As you can see, the print method aligns it fine but when I try to send it to my JList it messes up even though I am using the same code. How would I go about aligning it? I have tried playing with the values in String format = "|%1$-25s|%2$-25s|$%3$-10.2f|%4$-15s|%5$-13s|\\n"; but it doesn't seem to help.
The reason for your messed up alignment in the JList is because it uses (hopefully) a proportional font. You could use a monospaced one, but that will be ugly. You need to use columns in the JList (ie a table control).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.