Skip to content

Instantly share code, notes, and snippets.

Embed
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)
;root
; |-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
.getPath
.getPath
(map #(.getUserObject %))
listener)))))
(defn map->jtree
[map listener]
(let [[root-obj nodes] (first map)]
(doto (JTree. (doto (DefaultMutableTreeNode. root-obj)
(create-nodes nodes)))
(.. getSelectionModel
(setSelectionMode
TreeSelectionModel/SINGLE_TREE_SELECTION))
(with-listener listener))))
(defn display-tree
"A simple container and display frame to show a JTree for debugging"
[#^JTree tree]
(SwingUtilities/invokeLater
#(doto (JFrame. "TreeView")
(.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
(.setContentPane (JScrollPane. tree))
(.pack)
(.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}}}
println))
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.