【问题标题】:In Clojure creating a function that creates 'n' JButtons each with different 'actionPerformed' method in other namespace在 Clojure 中创建一个函数,该函数在其他命名空间中创建“n”个 JButton,每个 JButton 具有不同的“actionPerformed”方法
【发布时间】:2014-03-11 00:00:47
【问题描述】:

我已经从第 216 页的 Clojure 喜悦中改编了这个方法。

 (defn makeButton [txt func panel]
    (let [btn (JButton. txt) ] ;bfun (symbol func) ]
    (doto  btn
        (.addActionListener 
            (proxy [ActionListener] [] (actionPerformed [_] 
                (func))) ;(bfun)))
        ))
        (.add panel btn)
    ))

加上这个测试代码:

(defn fba [] (prn "fba"))
(defn fbb [] (prn "fbb"))
(def funs [fba fbb])
(def btnames ["B1" "B2"])

Buttons & actionPerformed 是在 gui 设置函数中创建的:

(doseq [i (range (count btnames)) ] 
              (makeButton (get btnames i) (nth funs i) aJpanel))

这可以按我的意愿工作;单击“B1”会打印字符串“fba”等。当我想将诸如ns1.ns2/myFunction 之类的附加到“actionPerformed”而不是这些简单的情况(即使用几个命名空间限定函数的列表/向量)时,我的困难就出现了。报告的异常是

传递给 Symbol 的 args (0) 数量错误

从上面的“makeButton”函数中,我尝试解决这个问题的方法被注释掉了。什么是惯用的 clojure 解决方案?

【问题讨论】:

  • 您需要做的就是将funs 中的一个函数替换为ns1.ns2/myFunction。如果您尝试这样做(不从工作版本修改makeButton)会发生什么?
  • 顺便说一句,我建议为您的标签/功能使用地图:(def foo {"B1" fba, "B2" fbb}),然后将您的按钮设为(doseq [[label f] foo] (make-button label f panel))
  • 感谢您对地图使用的有用建议。有时会回到旧的 Java 循环习惯。
  • 别担心,我自己还在学习 Clojure,所以我尝试找到看起来不像“Clojure”的代码。 :-)

标签: function clojure namespaces parameter-passing


【解决方案1】:

此代码在 REPL 中适用于我。我使用clojure.pprint/pprint 作为位于不同命名空间中的函数的示例:

(import '[javax.swing JFrame JPanel JButton]
        '[java.awt.event ActionListener])

(def panel (JPanel.))

(def frame (doto (JFrame. "Hello Frame")
             (.setContentPane panel)
             (.setSize 200 200)
             (.setVisible true)))

(defn make-button [label f panel]
  (let [button (JButton. label)]
    (doto button
      (.addActionListener
       (proxy [ActionListener] []
         (actionPerformed [evt]
           (f evt)))))
    (.add panel button)))

(make-button "One" clojure.pprint/pprint panel)

(.revalidate frame)

【讨论】:

  • 很奇怪,但你是对的,你的版本有效。感谢您的帮助。现在我必须确定我在哪里搞砸了。
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多