Question

I've got a list of objects of type Catalog. the class Catalog has a method called getName which returns the name of the object. I've got List<Catalogue> catalogList = /*code to retrieve list*/

I tried this but it did not work

JList  jlist = new JList(catalogList.toArray());

My question is how do I display the names in a Jlist?

Was it helpful?

Solution

Override the toString() method in your Catalogue class:

@Override
public String toString() {
    return getName();        
}

OTHER TIPS

Your JList contains instances of Catalog. By default, it uses the toString() method of the objects it contains to display them. So your first option is to override toString() in Catalog and make it return the name.

Another, more general and flexible option is to set a custom cell renderer, which the list will call to display every Catalog object. The Swing tutorial has examples.

You want your jlist to have only the names of the elements from catalogList? as I see you're trying to add Catalogue elements to the Jlist

JList  jlist = new JList();
for(int i=0;i<catalogList.size();i++){
     jlist.add(catalogList.get(i).getName();
}

Might be a more efficient way then this, but I think this is easier to understand

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top