开发者

Super simple java swing jlist question that I just can't figure out!

Ok, so I am working on a homework assignment, and I am using SWING to make a GUI for a Java project, and I am running into troubles with JList.

I have a customer object that I have made and set attributes to, and I want to add the object into a TreeMap. I want to hook up the Treemap so that any and all objects that are in the map will populate (the name attribute anyway) inside of the JList.

I have done a lot of looking around, and am seeing a lot about coding these things from scratch but little dealing with Swing implementation. I put my customer object into my map and then I would like for my JList to reflect the map's contents, but I don't know how to hook it up.

    customers.put(c.getName(), c);
    this.customerList.(What 开发者_运维百科can I do here? add Customer object?? I can't find what I need);

Thanks for your help!!!


You need to create a custom list model that returns objects to put in each row of a JList. TreeMap can't be accessed with an index, so you'll need something else. So the general idea is this: (from JList javadoc):

ListModel bigData = new AbstractListModel() {
    ArrayList customers;
    public int getSize() { return customers.size() }
    public Object getElementAt(int index) { return customers.get(index); }
};

JList bigDataList = new JList(bigData);

this way when you update your collection, just call revalidate() or repaint() on the JList and it will update its contents too.


so I am working on a homework assignment

So what exactly is the assignment about? You've given us your attempted solution, but since we don't know the actual requirement we can't tell if you are on the right track or not.

Are you forced to use a TreeMap to store the objects? Because this is not a good collection to use for your ListModel since you can't access the objects directly.

Or is the assignment simply about displaying data from an object in a JList? If so then you can use the DefaultListModel. All you need to do is override the toString() method of you custom object to have the "name attribute" show in the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜