How to create a JList that contains a hashtable entry for a string and an object?

I want to create a JList that contains Hashtable entries for a string and an object:

Hashtable<String,Object> 

The JList element must contain a hash table entry and display the value of the input key, which is a string ...

Is it possible? How can I do that?

+6
source share
4 answers

Deploy the ListModel interface by extending AbstractListModel . Use the derived model to create a JList . See Also How to use lists .

+5
source

Use the Hashtable key set for data in a 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()) 
+5
source

Hashtable is "old", so you should use HashMap instead.

You can get a collection of all values ​​in a Hashtable by calling values ​​(). OOPS - I read your question incorrectly, change it to keySet (). If you are happy with displaying them in a JList using their toString () method (for example, these are strings), just add them all to the JList. Unfortunately, JList designers, at least in J6, don’t take Collections (my favorite motive is how many Collections were around ???), so you have to work a little there.

One warning. Hashtable and HashMap organize their entries in a rather unpredictable way. Thus, the order of values ​​in a JList will almost certainly not be the order you want. Consider using LinkedHashMap or TreeMap to maintain a more reasonable order.

+5
source

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

+3
source

Source: https://habr.com/ru/post/905225/


All Articles