【发布时间】:2011-12-07 21:46:07
【问题描述】:
我有以下代码,旨在将键绑定映射添加到 JFrame。不幸的是,虽然它可以编译并且在运行程序时我没有收到任何错误,但绑定不起作用。
我错过了什么?
(defn create-action
"Returns an Action that, when called, executes the given fn."
[f]
(proxy [AbstractAction] []
(actionPerformed [e] (f))))
(defn init-jframe-key-bindings!
"Adds the keybindings to the frame.
keymap take the form of:
{\"KEYSTROKE\" [:key-name fn]
...}"
[frame keymap]
(let [actionmap (.getActionMap (.getRootPane frame))
inputmap (.getInputMap (.getRootPane frame) JComponent/WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)]
(doseq [[keystroke [keyword action]] keymap]
(.put actionmap (name keyword) (create-action action))
(.put inputmap (KeyStroke/getKeyStroke keystroke) (name keyword)))))
绑定是这样添加的:
(doto frame
(.setFocusable true)
(init-jframe-key-bindings!
{"RIGHT" [:next-view to-next-view]
"LEFT" [:prev-view to-previous-view]
"T" [:thresh-test conduct-thresh-test]
"A" [:add-marks #(dosync (ref-set ref-mark-mode :a))]
"D" [:del-marks #(dosync (ref-set ref-mark-mode :d))]}))
编辑解决方案是使用JComponent/WHEN_IN_FOCUSED_WINDOW 代替JComponent/WHEN_ANCESTOR_OF_FOCUSED_COMPONENT。我不确定为什么会这样,因为焦点应该满足成为焦点组件祖先的要求(但也许不是,我的无数组件是什么)并且仍然希望听到答案,但是有后人的解决方案。
【问题讨论】: