Search code examples
swingclojureseesaw

Clojure's Seesaw: How do I recognize that enter has been pressed


http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html#getKeyCode()

I don't know how to test if the key that was pressed was Enter. Using the following boiler plate and (alert ...). I've managed to determined that the event, e, is a KeyEvent and from its documentation I see there is a constant VK_Enter to represent Enter and three methods getKeyChar, getKeyCode and getKeyText. Using (alert e) It appears that getKeyChar returns Enter, or at least something that is represented with the Enter String, but (= (.getKeyChar e) "Enter") returns false. How can I detect that Enter was pressed?

(-> (frame :title "Zangalon" :content
           (text :text "Input Goes here"
                 :listen [:key-typed (fn [e] ..)]))
    pack!
    show!)

VK_Enter


Solution

  • A working example:

    (ns user
      (:require [seesaw.core :as ui]))
    
    (defn keypress [e]
      (let [k (.getKeyChar e)]
        (prn k (type k))
        (if (= k \newline)
          (prn "ENTER!")
          (prn "some other key"))))
    
    (defn run []
      (-> (ui/frame :title "Zangalon" :content
                    (ui/text :text "Input Goes here"
                             :listen [:key-typed keypress]))
          ui/pack!
          ui/show!))
    

    and the output:

    \q java.lang.Character
    "some other key"
    \w java.lang.Character
    "some other key"
    \e java.lang.Character
    "some other key"
    \newline java.lang.Character
    "ENTER!"
    \newline java.lang.Character
    "ENTER!"
    

    Event itself is:

    #<KeyEvent java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar=Enter,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=10,scancode=0,extendedKeyCode=0x0] ...>
    

    As you can see keyCode is 0 so .getKeyCode will not work.

    java version "1.7.0_25"
    Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
    Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)