Wait for the clojure key to be pressed

I created a java frame with a swing

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

and I would like to catch a user click.

I tried to compile the code here and there and ended up 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 that will not work. I am new to clojure, and since I know absolutely nothing about JAVA (and really don't want to enter it), I got a little lost. Is there an easy way to catch user input for keyboard shortcuts throughout the application?

help me please.

+4
source share
4 answers

If you just need to map specific keystrokes for different functions in a frame, seeaw.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 )) 

(all built on top of the @Bill key headers)

Take a look at the docs for map-key for more information. As mentioned in other answers, Swing's keyboard handling is even more unpleasant than the rest of Swing, so be prepared for some pain :)

+4
source

Seesaw is great, but it can still be a little difficult to find how to do what you want, especially if (like me) you are not a Swing expert. There is usually no need to crack the Java API, especially for something so simple. Here is 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 beautiful Seesaw tutorial has no example of a keystroke - it would be nice to add.

+3
source

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

Before you learn about this, you want to understand a little hesitation. Java Trail is a good place to start. http://docs.oracle.com/javase/tutorial/uiswing/index.html

+3
source

You have an e in your call to warn you that this is actually not the case. Should work without it. Good luck trying to use Clojure without learning Java, I don’t think it will work in the long run, but it would be nice if that happened.

0
source

Source: https://habr.com/ru/post/1445928/


All Articles