Using Java in Clojure and Lab 3

;; Clojure structures and java methods

;; a structure
(defstruct square :x-coord :y-coord :side)

;; a recursive function that creates the squares
(defn make-squares [x-coord y-coord side min-side]
  (if (< side min-side)
    (cons (struct square x-coord y-coord side)
	  (make-squares (+ x-coord (/ side 4))
			(+ y-coord (/ side 4))
			(/ side 2)

(def squares (make-squares 5 5 380 5))

;; now let's draw them!!!

(defn draw-square [graphics sq]
  (.drawRect graphics (:x-coord sq) (:y-coord sq) (:side sq) (:side sq))

(defn draw-sideways-square [graphics sq]
  (let [half-side (/ (:side sq) 2)
        x-half (+ (:x-coord sq) half-side)
        y-half (+ (:y-coord sq) half-side)
        x-other-side (+ (:x-coord sq) (:side sq))
        y-other-side (+ (:y-coord sq) (:side sq))
    (.drawLine graphics x-half (:y-coord sq) (:x-coord sq) y-half )
    (.drawLine graphics (:x-coord sq) y-half x-half y-other-side)
    (.drawLine graphics x-half y-other-side x-other-side y-half)
    (.drawLine graphics x-other-side y-half x-half (:y-coord sq))

;; Imports for working with Java
(import '(java.awt Color Dimension Graphics Point BorderLayout Graphics2D))
(import '(javax.swing JPanel JFrame  JLabel))

(def frame (JFrame.)) ; calling the constructor

(def my-panel
 (proxy [JPanel] [] ;; the class extends JPanel
     (repaint [] ;; overwrite the repaint method
       (let [gr (.getGraphics this)] 
         (.setColor gr Color/BLUE)
         (doall (map #(draw-square gr %1) squares))
         (.setColor gr Color/RED)
         (doall (map #(draw-sideways-square gr %1) squares))
         (println "Done") ; debugging print

(.setPreferredSize my-panel (Dimension. 400 400))

;; a sequence of methods on JFrame
(doto frame
  (.setSize 420 420)
  (.add my-panel BorderLayout/CENTER)
  (.add (JLabel. "    Draw squares") BorderLayout/SOUTH)
  (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
  (.setVisible true)

;; wait for a bit and then paint. Otherwise threads don't work right
(Thread/sleep 500)
(.repaint my-panel)

UMM CSci 4409

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.