
This is the result of querying the Cosmos status of a feed's url, the code itself is hardly 150 lines (half of it being the XML parsing to account for missing/null data). Because Groovy has blurred the line between beans and Maps getting a sorted, observable JTable model is quite easy. The first thing we require is an EventList, GlazedList's basic building block, basically it fires events whenever the list changes (even if the element's properties change too). With GlazedLists you can update your data as you'd like and all the adapters and connectors will update the UI at the appropriate time, with that in mind we create the EventList as follows
That's right, we are taking advantage of Groovy's powerful
as
keyword to coerce a closure into a dynamic proxy of a Comparator, in this case will sort elements based on their name
property, which may anything that implements the Comparable interface (such as Strings). The second step is to wire a JTable with the list, say what? exactly join a List with a JTable. GlazedLists has several ways of doing so, I'm going to show the one using a helper class: EventTableModel
and its companion: TableFormat
. This interface is responsible for expanding each element of the list into the proper row values it represents. In the case of the Technorati stats gatherer, each list element is actually a Map with 4 properties: name, url, blogs and links; each column will use the capitalized property name as its header, thus making our job a lot simplerAgain we reuse the coercion trick but this time with a Map, it is so simple and addictive it should be illegal (or criminal as Shemnon recently said). Remember that this trick has a drawback: no inheritance (unless you use method pointers which tend to muck the trick). This is one of the reasons I rarely miss inner classes when using Groovy. Back to the code, the next step is wiring up the table and enabling the sorting mechanism, if you were expecting complicated code here please go to your regular Java Swing cookbook examples, no such thing here!
Yup, it only takes one line! Now we are able to update the data as we see fit, the connectors/adapters from GlazedLists and Swing will take care of updating the UI, our Technorati stats gatherer does it in the following manner
So there you have it. If your daily work includes mangling data back and forth with Lists and TableModels, please consider using GlazedLists (with Groovy it is even better) and stop the Swing pain.
Keep on Groovying!