简体   繁体   中英

Get selected value JList or List in Java Swing, stuck with getElementAt() of ListModel

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

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, (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM