How to copy a static HashMap into a JTable
Join the DZone community and get the full member experience.
Join For FreeIt was a sunny day with easy code and birds singing. But, suddenly a static HashMap (it could be non-static, also) wants to be copied into a two column JTable, keys on first column, and values on the second one. Well, the clouds start to press and before I notice it starts to rain … "with questions":
- How to delete all rows of a JTable (I need this because sometimes I have to refresh the JTable for 0) ?
- How to obtain the keys from the JTable by index, or similar?
- How to add or insert the HashMap elements into JTable ?
public class MyMapHostClass { ... public static Map myMap = new HashMap(); ... }
Afterwards, it proves to be a summer rain, warm and refreshing, because the answers jump up in a few minutes: delete all rows using a backward loop (or a nice trick) – both here, get all keys with the keySet method, and insert/add them into JTable with insertRow/addRow method. Well, I glue all these answers into lines code, and get this:
... DefaultTableModel model = (DefaultTableModel) jTable.getModel(); ... //remove all rows model.getDataVector().removeAllElements(); ... //get all keys – notice the static effect, you can use it for non-static HashMap either Set keys = MyMapHostClass.myMap.keySet(); //get an Iterator over keys Iterator iteratorKeys = keys.iterator(); //put them into jTable while (iteratorKeys.hasNext()) { String key = (String) iteratorKeys.next(); //insert on first position by pushing down the existing rows model.insertRow(0, new Object[]{key, MyMapHostClass.myMap.get(key)}); //append at the end model.addRow(new Object[]{key, MyMapHostClass.myMap.get(key)}); }
Done! Now, is still raining, but … I’m singing in the rain!
From http://e-blog-java.blogspot.com/2011/03/how-to-copy-static-hashmap-into-jtable.html
Data structure
Opinions expressed by DZone contributors are their own.
Comments