6

I want to create a JList that contains entries of a Hashtable of String and object :

Hashtable<String,Object>

the JList element should contain the hashtable entry and display the value of the entry key that is a string ...

Is it possible ? How can it be done ?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
aleroot
  • 71,077
  • 30
  • 176
  • 213

4 Answers4

5

Implement the ListModel interface by extending AbstractListModel. Use the derived model to create your JList. See also How to Use Lists.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • By coding to the `Map` interface, one has more latitude to select an alternate implementation, such as `SortedMap`. – trashgod Jan 05 '12 at 18:29
  • 1
    +1 but... This is more work than @dogbane and my solution. However, if the Hashtable is going to change over time and you need to dynamically update the JList, this is the way to go. – user949300 Jan 05 '12 at 18:32
  • 1
    Yes, the JList is going to change because the user can interact with it, so this is the way to go. I asked because i was hoping that there was a less work to do solution, but unfortunately not . Thanks to all for the help. I will implement an HastTable ListModel ;) . – aleroot Jan 05 '12 at 19:37
  • See also this [example](http://stackoverflow.com/a/9134371/230513) that builds a `TableModel` around `Map`. – trashgod Aug 28 '12 at 15:47
5

Use the keyset of your Hashtable for the data in your JList:

Hashtable<String, Object> table = new Hashtable<String, Object>();
JList list = new JList(table.keySet().toArray());

You can also call:

list.setListData(table.keySet().toArray())
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 1
    I like the simplicity of this solution. But be warned that the order of the keySet will be pretty random, so the order of items in the JList will not be what @aleroot expects. – user949300 Jan 05 '12 at 18:26
5

Hashtable is "old", so you should consider using a HashMap instead.

You can get a Collection of all the values in the Hashtable by calling values(). OOPS - I misread your question, change that to keySet(). If you are happy with displaying them in the JList using their toString() method (e.g., they are Strings), just add them all to the JList. Unfortunately, the JList constructors, at least in J6, do not take Collections (pet peeve of mine - how many years have Collections been around???), so you'll have to do a little work there.

One warning. Hashtable and HashMap order their entries in a pretty unpredictable manner. So the order of the values in the JList will almost certainly not be the order you want. Consider using a LinkedHashMap or a TreeMap to maintain a more reasonable ordering.

user949300
  • 15,364
  • 7
  • 35
  • 66
3

You can implement the ListModel interface to do anything you want. Create a class that implements it and holds onto your desired HashMap. Pay particular attention to the getElementAt method implementation.

Perception
  • 79,279
  • 19
  • 185
  • 195