RNO
RNO

Reputation: 223

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?

Upvotes: 0

Views: 2903

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347194

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

Upvotes: 3

Brian
Brian

Reputation: 7326

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();
  }
}

Upvotes: 1

Related Questions