Searching for Signal

the n01se blog

Is it hard to write a GUI in Clojure?


Exploring a parsed XML file using the gview function

Of course a screenshot doesn't prove something's easy. How about the complete codebase needed to make the screenshot?

(ns gview
  (:import (javax.swing JFrame JScrollPane JTree)))

(defn- make-node [parent obj]
  (proxy [javax.swing.tree.TreeNode] []
    (toString []          (pr-str obj))
    (getAllowsChildren [] (coll? obj))
    (getChildAt [i]       (make-node this (nth (seq obj) i)))
    (getChildCount []     (count obj))
    (getIndex [n]         -1)
    (getParent []         parent)
    (isLeaf []            (not (coll? obj)))))

(defn gview [obj]
  (doto (JFrame.)
    (add (JScrollPane. (JTree. (make-node nil obj))))
    (setTitle (str "gview: " (.getName (class obj))))
    (setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
    (setVisible true)))

With that, you've got a handy gview function you can call from the REPL whenever you want. Trying to make sense of the in-memory representation of an messy XML file? Or maybe just trying to reproduce my screenshot? Just type this at the REPL:

(gview (clojure.xml/parse "/etc/tomcat5.5/web.xml"))

Update 23 Jan 2009: Clojure has for quite a while come with a strikingly similar tool built right in:

(use 'clojure.inspector)
(inspect-tree (clojure.xml/parse "/etc/tomcat5.5/web.xml"))