Override the toString() method in your Catalogue class:
@Override
public String toString() {
return getName();
}
Pergunta
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?
Solução
Override the toString() method in your Catalogue class:
@Override
public String toString() {
return getName();
}
Outras dicas
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