It turns out that the MouseInputAdapter is the best class to use for drawing by toggling the icons. It took me forever to get the mouse button code right. Aaargh!
I’m happy about the little code reorganization, reusing the instances of ImageIcon and MouseInputAdapter.
The result already allows me to toggle between floor tiles and empty tiles:
My next plan: Use ’d’ to switch to drawing a door tile. I’ll need to figure out how to rotate the door tile, and how to display the current ’mode’ in some sort of status bar.
(import '(javax.swing JLabel JPanel JFrame ImageIcon) '(javax.swing.event MouseInputAdapter) '(java.awt GridBagLayout GridBagConstraints) '(java.awt.event InputEvent)) (def EMPTY_TILE (ImageIcon. "empty.png")) (def FLOOR_TILE (ImageIcon. "floor.png")) (defn empty-tile [] (JLabel. EMPTY_TILE)) (defn floor-tile [] (JLabel. FLOOR_TILE)) (defn get-tile [] "Return the tile the user wants to place. By default this will be a FLOOR_TILE." FLOOR_TILE) (defn edit-grid [e] "Draw a tile at the position of the event E. If the button is pressed, and the tile is empty, use GET-TILE to determine which tile to draw. Otherwise, erase the current tile and place an EMPTY_TILE." (let [cell (.getComponent e)] (if (.equals (.getIcon cell) EMPTY_TILE) (.setIcon cell (get-tile)) (.setIcon cell EMPTY_TILE)))) (defn mouse-input-adapter [] "A MouseInputAdapter that will call EDIT-GRID when the mouse is clicked or dragged into a grid cell." (proxy [MouseInputAdapter] [] (mousePressed [e] (edit-grid e)) (mouseEntered [e] (let [mask InputEvent/BUTTON1_DOWN_MASK] (if (= mask (bit-and mask (.getModifiersEx e))) (edit-grid e)))))) (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 [constraints (GridBagConstraints.) adapter (mouse-input-adapter)] (loop [x 0 y 0] (set! (. constraints gridx) x) (set! (. constraints gridy) y) (. panel add (doto (empty-tile) (.addMouseListener adapter) (.addMouseMotionListener adapter)) constraints) (cond (and (= x width) (= y height)) panel (= y height) (recur (+ x 1) 0) true (recur x (+ y 1)))))) (defn app [] (let [frame (JFrame. "Grid Mapper") panel (doto (JPanel. (GridBagLayout.)) (simple-grid 5 5))] (doto frame (.setContentPane panel) (.pack) ;; (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.setVisible true)))) (app)
#Clojure
(Please contact me if you want to remove your comment.)
⁂
I need to look into Leiningen and Clojars. There is a nice tutorial available from Alex Osborne.
tutorial available from Alex Osborne
I managed to add a keyboard adapter to switch between floor and door drawing.
Next I need to figure out whether drawing a door at the current position is legal, and whether it should be a north-south or an east-west door. Right now the cells on the grid have no understanding of neighborhood. Interesting times! :D
– Alex