001package edu.pdx.cs410J.family; 002 003import java.util.*; 004import javax.swing.*; 005 006/** 007 * A <code>FamilyTreeList</code> is a <code>JList</code> that contains 008 * the names of the people in a family tree. 009 */ 010@SuppressWarnings("serial") 011public class FamilyTreeList extends JList { 012 private Map<Integer, Person> indexToPerson = new HashMap<Integer, Person>(); 013 014 /** 015 * Creates a <code>JList</code> populates it with the name of 016 */ 017 public FamilyTreeList() { 018 this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 019 this.clearSelection(); 020 } 021 022 /** 023 * Fills in the <code>JList</code> with the contents of a 024 * <code>FamilyTree</code>. 025 */ 026 public void fillInList(FamilyTree tree) { 027 SortedSet<Person> sortedPeople = new TreeSet<Person>(new Comparator<Person>() { 028 // Sort id's from lowest to highest 029 030 public int compare(Person p1, Person p2) { 031 return p1.getId() - p2.getId(); 032 } 033 034 public boolean equals(Object o) { 035 return true; 036 } 037 }); 038 039 sortedPeople.addAll(tree.getPeople()); 040 String[] array = new String[sortedPeople.size()]; 041 042 Iterator iter = sortedPeople.iterator(); 043 for (int i = 0; iter.hasNext(); i++) { 044 Person person = (Person) iter.next(); 045 array[i] = person.getFullName() + " (" + person.getId() + ")"; 046 indexToPerson.put(new Integer(i), person); 047 } 048 049 this.setListData(array); 050 this.clearSelection(); 051 } 052 053 /** 054 * Returns the currently selected person. 055 */ 056 public Person getSelectedPerson() { 057 return this.indexToPerson.get(this.getSelectedIndex()); 058 } 059 060 /** 061 * Sets the selected person. 062 */ 063 public void setSelectedPerson(Person person) { 064 Integer index = null; 065 Iterator iter = this.indexToPerson.entrySet().iterator(); 066 while (iter.hasNext()) { 067 Map.Entry entry = (Map.Entry) iter.next(); 068 if (entry.getValue().equals(person)) { 069 index = (Integer) entry.getKey(); 070 } 071 } 072 073 if (index == null) { 074 return; 075 076 } else { 077 this.setSelectedIndex(index.intValue()); 078 } 079 } 080 081}