display list using DefaultListModel and JList

2019-08-13 17:59发布

问题:

I am trying to display a list of items using DefaultListModel and JList but my window is empty. What is the error?

see code:

    public class ViewInventoryInterface extends JFrame {
    private Inventory theInventory; // reference to back end
    private InventoryUPCIterator iter;
    private DefaultListModel dlm;
    private JList list;
    private JScrollPane scroll;

    public ViewInventoryInterface(Inventory theInventory) {
        this.theInventory = theInventory;
        iter = theInventory.inventoryUPCIterator(); //returns an iterator for the inventory
        dlm = new DefaultListModel();
        while (iter.hasNext()) {
            dlm.addElement(iter.next().toString());
        }
        list = new JList(dlm);
        scroll = new JScrollPane(list);
        setTitle("Inventory");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);    
    }
} 

回答1:

A first problem might be that you're not adding anything to your frame. Use getContentPane().add(...) etc. to add your scroll pane to the frame.

Depending on the layout manager you might need to have different additional parameters but with the default BorderLayout just adding should work.