S'identifier - S'inscrire - Contact

CommunityWiki
Jam session in wikilandia

Clojure Mouse Listener

Source :

Ok, so I got a bit further compared to last time. As you can see I got rid of that fancy macro and decided to just write simple code that works for this particular situation. And it works. (import '(javax.swing JLabel JPanel JFrame ImageIcon) '(java.awt.event MouseListener) '(java.awt GridBagLayout GridBagConstraints))

(defn empty-tile [] (JLabel. (ImageIcon. "empty.png")))

(defn floor-tile [] (JLabel. (ImageIcon. "floor.png")))

(defn simple-grid [panel width height] "creates a grid of WIDTH + 1 columns and HEIGHT + 1 rows where each cell contains the result of a call to (EMPTY-TILE) and adds it to the PANEL" (let [c (GridBagConstraints.)] (loop [x 0 y 0] (set! (. c gridx) x) (set! (. c gridy) y) (. panel add (empty-tile) c) (cond (and (= x width) (= y height)) panel (= y height) (recur (+ x 1) 0) true (recur x (+ y 1))))))

(defn app [] (let [frame (proxy [JFrame MouseListener] ["Grid Mapper"] (mouseClicked [e] (println e))) panel (doto (JPanel. (GridBagLayout.)) (simple-grid 5 5))] (doto frame (.setContentPane panel) (.pack) ;; (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.setVisible true))))

(app)My problem right now is that the mouseClicked code is never called. I wonder why. [1] [2]It turns out that I needed to call addMouseListener at some place. So app changed:(defn edit-grid [e] "placeholder" (println e))

(defn mouse-listener [] "A mouse listener that will call EDIT-GRID when the mouse is clicked" (proxy [MouseListener] [] (mouseClicked [e] (edit-grid e)) (mouseEntered [e]) (mouseExited [e]) (mousePressed [e]) (mouseReleased [e])))

(defn app [] (let [frame (JFrame. "Grid Mapper") panel (doto (JPanel. (GridBagLayout.)) (simple-grid 5 5))] (doto frame (.addMouseListener (mouse-listener)) (.setContentPane panel) (.pack) ;; (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.setVisible true))))If I don’t implement all of the MouseListener interface, I end up getting a ton of exceptions whenever the mouse entered or exited the frame and whenever the button was pressed or released. It felt weird adding all those empty methods [..]

le 05.06.10 à 13:38 dans Mind - Version imprimable
Article précédent - Commenter - Article suivant -