简体   繁体   中英

Wait for a keypress in clojure

I created a java frame with seesaw

(def f (frame :title "my app"))

and I would like to catch user keypress.

I tried to gather code here and there and ended with this

(ns myapp.core
  (:use seesaw.core)
  (:use seesaw.font)
  (:import [java.awt.event ActionListener KeyListener KeyEvent])
)

(defn input-listener []
(proxy [ActionListener KeyListener] []
  (actionPerformed [e])
  (keyPressed [e] (alert e "You pressed a key!"))
  (keyReleased [e])
  (keyTyped [e])))

(doto f
  (.addKeyListener (input-listener)))

but it won't work at all. I am new to clojure and since I absolutely don't know anything JAVA (and don't really want to ding into it) I am a bit lost. Is there a simple way to catch user input for keyboard shortcuts in the whole app ?

help please.

If you'd just like to map specific key presses to different functions in a frame, seesaw.keymap/map-key is probably what you want:

; When 'e' is pressed in frame f, call this function
(map-key f "e" (fn [_] (... do something ))

(this is all built on top of the keybinding stuff @Bill references)

Take a look at the docs for map-key for more info. As the other answers have alluded to, keyboard handling in Swing is even nastier than the rest of Swing so be ready for some pain :)

Seesaw is great, but it can still be a bit tricky to find how to do what you want, particularly if (like me) you're not a Swing expert. Usually breaking into the Java API isn't needed, particularly for something this simple. Here's what worked for me:

(ns so.core
  (:use seesaw.core))

(let [f (frame :title "my app")
      handler (fn [e] (alert "pressed key!"))]
  (listen f :key-pressed handler)
  (show! f))

Unfortunately this nice Seesaw tutorial doesn't have a keypress example -- would be good to add.

If you want to globally intercept keys in a swing application, you need a KeyEventDispatcher , which you would register through the KeyboardFocusManager . If you want to add actions based on keys to specific components (much higher level - much better), you probably want KeyBindings http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Before you learn seesaw though, you want to understand a little bit of swing. The Java Trail is a good place to start. http://docs.oracle.com/javase/tutorial/uiswing/index.html

You got an e in your call to alert that doesn't really belong there. Should work without it. Good luck with trying to use Clojure without learning Java, I don't think it's going to work out on the long run but it'd be nice if it did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM