Adding objects to a JList

Jim_CS picture Jim_CS · Mar 1, 2012 · Viewed 11.2k times · Source

I have an object - ArrayList<User> users that contains a few user objects.

public class User
{
    int id;
    String name;
    String location;
}

I want to put this ArrayList in a JList so it will display the users names -

John
Mick
Sam
Joe

--- And when I select a user name an event is fired that lets me perform some action using the appropriate User object. So someone clicks 'Mick' and I get code like this (pseudocode) -

public jListClicked(User user)
{
    int id = user.id;
    String name = user.name;
    String location = user.location;

    updateDatabase(id, name, location);
}

I presume this is possible using a JList?? After all I imagine that is what the JList component was created for. So how do I add an object like ArrayList to a JList so I will have the above functionality?

Answer

Tony picture Tony · Mar 1, 2012

A JList takes in one of its constructor an Object[]. You can get this from your ArrayList with the .toArray() function. I believe (I could be wrong...) that if your User class overrides the toString() method, the JList will use this when it displays your object.

public class User
{
    int id;
    String name;
    String location;

    public String toString() {
      return name;
    }
}

I would recommend reading the documentation for JList in the java docs. It has an example of how to build a custom cell renderer to display items in your list the way you want them displayed. It's pretty easy to follow. It also has an example of how to create the mouse click listener. You should be able to copy/paste this for the most part.

http://docs.oracle.com/javase/6/docs/api/