display list using DefaultListModel and JList

a 夏天 提交于 2019-12-24 09:37:26

问题


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.



来源:https://stackoverflow.com/questions/7878697/display-list-using-defaultlistmodel-and-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!