简体   繁体   English

Java字符串格式

[英]Java String format

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. 我试图创建一个与JList一起使用的字符串数组,我的Book类中有一个对象数组,其中包含作者名称,Tittle等...但是当我使用string.format并将其发送给我的JList时不会像我使用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. 如您所见,print方法可以很好地对齐它,但是当我尝试将其发送到JList时,即使我使用的是相同的代码,它也会弄乱。 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"; 我尝试过使用String格式的值=“ |%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. 在JList中弄乱对齐的原因是因为它(希望)使用了比例字体。 You could use a monospaced one, but that will be ugly. 您可以使用等距的一个,但是这样很难看。 You need to use columns in the JList (ie a table control). 您需要使用JList中的列(即表控件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM