简体   繁体   中英

Display JList elements from model

I have a list of Objects Person (int age, String name) that are stored in a DefaultListModel to be assigned to the JList .

DefaultListModel model;
model = new DefaultListModel();

Person p = new Person(43,"Tom");
//insert in the model
model.add(size, p);

jList1.setModel(model);

I would like to display only the name in the JList , but I cannot figure out how to do it without using another list of Names (which I would prefer to avoid).

Is there any easy way to tell the JList which attribute of the object Person to display?

The display of the view should be the domain of the ListCellRenderer

Something like...

public class PersonCellRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof Person) {
            setText(((Person)value).getName());
        }
        return this;
    }
}

To apply the render to the list, you need to do...

jList1.setCellRenderer(new PersonCellRenderer());

Take a look at Writing a Custom Cell Renderer for more information

Simply override the toString() method of your Person class to return the name of the Person

DefaultListModel model;
model = new DefaultListModel();

Person p = new Person(43,"Tom");
//insert in the model
model.add(size, p);

jList1.setModel(model);

public class Person {

  private int age;
  private String name;

  public Person(int age, String name) {
    this.age = age;
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public String toString() {
    return this.getName();
  }
}

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