简体   繁体   中英

How do I format text within a JList?

I have items in a JList that I can't get to format correctly.

I've created this method in order to do so:

private String formatString(String string){
     string = string.trim();

    int SEPERATOR = 20 - string.length();

    for(int i = 0; i<SEPERATOR; i++){

        string = string + " ";
    }

    return string;
}

When I output the items in my JList into the output window using a system out print it formats fine, but in my GUI it does not:

例

I'm not sure if this will help you help me better but here is how I am loading my data into the list:

    DefaultListModel m = new DefaultListModel();

    while (rs.next()){

        String Expense = rs.getString("Expense");
        String Cost = "£"+rs.getString("Cost");
        String PurchaseDate = rs.getString("Purchase_Date");
        String Description = rs.getString("Description");

        Expense = formatString(Expense);
        Cost = formatString(Cost);
        PurchaseDate = formatString(PurchaseDate);
        Description = formatString(Description);


        String Row = Expense+Cost+PurchaseDate+Description;

        m.addElement(Row);
        System.out.println(Row);
    }

The best solution, as has already been suggested, is to use a JTable . Read the section from the Swing tutorial on How to Use Tables for more information and working examples.

When i output the items in my jlist into the output window using a system out print it formats fine, but in my GUI it does not:

To answer your question you need to use a monospaced font.

list.setFont( new Font("monospaced", Font.PLAIN, 10) );

Also, use standard Java variable names. Variable name (Expense, Cost...) should NOT start with an upper case character.

您可以使用\\ t(如果字段的文本太长,则可能必须使用/ t / t)而不是使用空格或使用JTable

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.

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