2

I have a method that returns a HashMap, and is defined as follows;

public HashMap<Integer, Animal> allAnimal(){

      return returnsAHashMap;
   }

Animal will have the following values in its class:

public Animal{

int animalID;
String animalName;

// i have declared getters/setters
}

I have a GUI screen which has a JList and it's defined as:

l = new JList();
l.setModel(new AbstractListModel() {

        String[] v = new String[] {"animal id 1", "2", "3"};
        public int getSize() {
            return v.length;
        }
        public Object getElementAt(int index) {
            return v[index];
        }
    });

What I want to do is to display the AnimalID's in the JList. I need to find a way to call the allAnimal() method and display all its Animal Id's in the JList. How can i do this ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

2 Answers2

1

you can try:

public int getSize() {
    return allAnimal().size();
}
public Object getElementAt(int index) {
    return allAnimal().keySet().toArray()[index];
}

or can try:

        String[] v = null;
        v = allAnimals().keySet().toArray(v);
        public int getSize() {
            return v.length;
        }
        public Object getElementAt(int index) {
            return v[index];
        }
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
1

Your AbstractListModel is anonymous, so first promote it to a named class, e.g. MyListModel. Then add a method to MyListModel that either accepts a Map or calls allAnimal() to obtain one. Once you have a reference to the Map in your model, you can convert the keySet to an array, as shown here, and use the keys to get() each Map entry in getElementAt(). Optionally, sort the array using Arrays.sort().

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • It's not clear what your keys represent; you may be better off iterating over the `entrySet()`. Please edit your question to include an [sscce](http://sscce.org/) that shows a _small_ number of typical `Map` entries. – trashgod Dec 10 '12 at 11:16