Skip to content

Instantly share code, notes, and snippets.

@michalmarczyk
Forked from Licenser/gist:385022
Created May 1, 2010 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalmarczyk/386761 to your computer and use it in GitHub Desktop.
Save michalmarczyk/386761 to your computer and use it in GitHub Desktop.
(ns clj-swing.core)
(import '(javax.swing JFrame JLabel JTextField JButton JComboBox JPanel Timer)
'(java.awt.event ActionListener)
'(java.awt GridBagLayout GridLayout GridBagConstraints))
(require '[clojure.contrib.java-utils :as java])
(defmacro combo-box [[& items] & actions]
`(doto (JComboBox.)
~@(map #(list '.addItem %) items)
~@actions)))
(defmacro set-text! [component text]
`(. ~component setText ~text))
(defmacro button [n caption listener-fn & actions]
`(let [~n (JButton. ~caption)]
(doto ~n
(.addActionListener
(proxy [ActionListener] []
(actionPerformed [~'event]
~listener-fn)))
~@actions)))
(defmacro label [caption]
`(JLabel. ~caption))
(defmacro panel [& args]
`(JLabel. ~@args))
(defmacro set-constraint! [constraints field value]
`(set! (. ~constraints ~(symbol (name field)))
~(if (keyword? value)
`(java/wall-hack-field (class ~constraints) '~(symbol (name value)) (class ~constraints))
value)))
(defmacro frame [title layout-manager constrain-object [& items] & actions]
(if (odd? (count items))
(throw (Exception. "items must be a even number"))
(let [frame (gensym "frame")
constrains (gensym "constrains")
manager (gensym "manager")]
`(let [~manager ~layout-manager
~frame (doto (JFrame. ~title)
(.setLayout ~manager))
~constrains ~constrain-object
~@(reverse
(reduce
(fn [l [f s]]
(if (keyword? f)
(conj (conj l '_) `(if ~constrains (set-constraint! ~constrains ~f ~s)))
(conj (conj (conj (conj l f) s) '_) `(if ~constrains (.add ~frame ~f ~constrains) (.add ~frame ~f)))
))
'() (partition 2 items)))]
(doto ~frame
~@actions)))))
(defn draw-sort [c alg]
(set-text! c alg))
(defn grid-sort-app []
(frame "Sort Visualizer" (GridLayout. 2 2 2 2) nil
[algorithm-chooser (combo-box ["Quick sort" "Bubble Sort"])
canvas (label "")
l1 (label "Algorithms")
l2 (label "Button")
button (button b "Run Algorithm"
(draw-sort canvas (.toString (.getSelectedItem algorithm-chooser))))]
(.setSize 250 250)
(.setVisible true)))
(defn grid-bag-sort-app []
(frame "Sort Visualizer" (GridBagLayout.) (java.awt.GridBagConstraints.)
[:gridx 0 :gridy 0 :anchor :LINE_END
l1 (label "Algorithms")
:gridy 1
l2 (label "Button")
:gridy 2
canvas (label "")
:gridx 1 :gridy 0 :anchor :LINE_START
algorithm-chooser (combo-box ["Quick sort" "Bubble Sort"])
:gridy 1
button (button b "Run Algorithm"
(draw-sort canvas (.toString (.getSelectedItem algorithm-chooser))))]
(.setSize 300 300)
(.setVisible true)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment