Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding objects to a JList

Tags:

java

swing

jlist

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?

like image 474
Jim_CS Avatar asked Mar 01 '12 01:03

Jim_CS


1 Answers

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/

like image 194
Tony Avatar answered Sep 23 '22 14:09

Tony