Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
JTree from a clojure collection
; Turn a map into a JTree
; keys can be any object using toString to display
; listener is called as (listener seq-of-keys-to-selected-node)
; |-child-1
; | |-Child-1-1
; | |-child-1-2
; |-child-2
; |-child-3
; |-child-3-1
{"root" {"child-1" {"child-1-1" nil
"child-1-2" nil}
"child-2" nil
"child-3" {"child-3-1" nil}}}
(import [javax.swing.tree DefaultMutableTreeNode TreeSelectionModel]
[javax.swing JFrame JTree JScrollPane SwingUtilities])
(defn create-nodes [root coll]
(doseq [[obj sub-nodes] (seq coll)
:let [node (DefaultMutableTreeNode. obj)]]
(.add root node)
(if sub-nodes (create-nodes node sub-nodes))))
(defn with-listener [tree listener]
(.addTreeSelectionListener tree
(proxy [javax.swing.event.TreeSelectionListener] []
(valueChanged [event] (->> event
(map #(.getUserObject %))
(defn map->jtree
[map listener]
(let [[root-obj nodes] (first map)]
(doto (JTree. (doto (DefaultMutableTreeNode. root-obj)
(create-nodes nodes)))
(.. getSelectionModel
(with-listener listener))))
(defn display-tree
"A simple container and display frame to show a JTree for debugging"
[#^JTree tree]
#(doto (JFrame. "TreeView")
(.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
(.setContentPane (JScrollPane. tree))
(.setVisible true))))
(display-tree (map->jtree
{"root" {"child-1" {"child-1-1" nil
"child-1-2" nil}
"child-2" nil
"child-3" {"child-3-1" nil}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.