Over a million developers have joined DZone.

How to copy a static HashMap into a JTable

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

It 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 ?
Oh, sorry, I forgot to introduce you my static HashMap, nothing special, just a trivial one – the elements are irrelevant, therefore I’ll skip it:
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
//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

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}