/
dynamic.clj
59 lines (53 loc) · 1.77 KB
/
dynamic.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
(ns tikkba.examples.dynamic
(:use clojure.pprint
[analemma svg charts xml]
[tikkba swing dom core]
tikkba.utils.xml)
(:require [tikkba.utils.dom :as dom])
(:import (javax.swing JFrame SwingUtilities)))
(defn create-svg
"Creates a SVG representation with the Analemma functions"
[]
(svg
(-> (rect 20 30 100 400 :id "rect0")
(style :fill "white" :stroke "blue" :stroke-width 10))
(-> (rect 50 250 50 80 :id "rect1")
(style :fill "white" :stroke "red" :stroke-width 10))
(-> (text "Click inside the blue rectangle!")
(add-attrs :x 450 :y 80)
(style :font-size "20px"))))
(defn random-color
[]
(letfn [(color
[]
(Integer/toHexString (rand-int 16)))]
(apply format "#%s%s%s%s%s%s" (repeatedly 6 color))))
(defn click-listener
[event canvas doc]
(let [rect1 (dom/element-by-id doc "rect1")
x (Integer/parseInt (dom/attr rect1 :x))]
;; changes rectangle position and color
(do-batik
canvas
(dom/add-attrs rect1
:style (style-str :fill (random-color))
:x (+ x 10)))))
(defn create-frame
[canvas]
(let [frame (JFrame.)]
(.add (.getContentPane frame) canvas)
(.setSize frame 800 600)
(.setDefaultCloseOperation frame JFrame/EXIT_ON_CLOSE)
;; or use the do-swing macro of clojure.contrib.swing-utils:
(SwingUtilities/invokeAndWait
(fn [] (.setVisible frame true)))))
(defn -main
[]
;; Converts the SVG representation to a XML Document
;; and displays the SVG in a JFrame
(let [doc (svg-doc (create-svg))
rect (dom/element-by-id doc "rect0")
canvas (jsvgcanvas)]
(dom/add-event-listener rect "click" click-listener canvas doc)
(set-document canvas doc)
(create-frame canvas)))