Reputation: 1952
i am using Swing List control to bind data, I (must) use a class to make the model
public class SubjectListModel extends AbstractListModel<String> {
public ArrayList<Subject> listSubjects;
public SubjectListModel(ArrayList<Subject> listSubjects) {
this.listSubjects = listSubjects;
}
@Override
public int getSize() {
return listSubjects.size();
}
@Override
public String getElementAt(int index) {
return listSubjects.get(index).name;
}
class Subject{
int id;
string name;
}
I wish to use the List to bind my ArrayList, Can I set something like "display text field" for "name" field, and "value field" for my "id"? So that I can retrieve those values as needed. The best dream is I can retrieve whole the selected "Subject" instead of a string field. I seen the list only have getSelectedValue, and if I want to display the subject in the List, I must set getValueAt() in model to return the "name", and getSelectedValue() return the selected "name" too :( If I change getElementAt() in model class to return "Subject", the list will display @object.abxdef
Upvotes: 1
Views: 1828
Reputation: 209052
Just override toString()
of Subject
, and return what ever you want to be displayed in the list. Then add all your Subject
instances to the list. No need for a custom ListModel
. Just use a DefaultListModel
. When you get the selected Subject
just use one of it's getters to the field you want.
Also no need to store your object in two locations, (i.e. the ListModel and the ArrayList) just add everything to the model.
class Subject {
private int id;
private String name;
public Subject(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
@Override
public String toString() {
return name;
}
}
DefaultListModel model = new DefaultListModel();
model.addElement(new Subject(1, "Math"));
Subject subject = (Subject)model.getElementAt(0);
System.out.println(subject);
// result -> Math
Upvotes: 2