javaswingjlistlistcellrenderer

Show object members inside JScrollPane


I have a list of objects using the default list model, like so:

public static DefaultListModel<Loan> loans = new DefaultListModel<Loan>();

My Swing application looks like this:

Image of my swing application

When the Add button is clicked, it creates a Loan object and adds that object to the DefaultListModel, like so:

addLoan.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Loan loan = Calculator.createLoan(
                Double.parseDouble(loanAmount.getText()),
                Double.parseDouble(interestRate.getText()),
                Double.parseDouble(term.getText())
        );

        Calculator.addALoan(loan); 
    }
});

With my code now, the objects actually appear in the JScrollPane fine. You can see below:

JList loanList = new JList(Calculator.loans);
loans = new javax.swing.JScrollPane(loanList);

The above code happens in my init method. This is what I see on the frontend:

enter image description here

I want to tab it out and show each of the members inside that box (scroll pane). A Loan object consists of amount, interest rate and term. I tried something similar to (How to dd an object to the JList and show member of the object on the list interface to the user?) but I am confused on how the renderer in the accepted answer shows up.


Solution

  • You are seeing the result of Swing’s default behavior. Swing is calling toString() on each Loan object.

    You can override that method to return something suitable for display:

    public class Loan {
        // (property methods)
    
        @Override
        public String toString() {
            return String.format("%12s    %6s    %,.1f years",
                NumberFormat.getCurrencyInstance().format(
                    getAmount()),
                NumberFormat.getPercentInstance().format(
                    getInterestRate() / 100),
                getTerm());
        }
    }
    

    Since JList uses a proportional width font on most platforms, the values from the loan objects probably won’t line up with each other. To address that, remove your JList, remove your list model, and instead subclass AbstractTableModel and use a JTable as camickr suggested.