我现在正在钻研Cljfx。但我遇到了一个问题:无法理解渲染器是如何工作的。我想按钮的文本将改变后,用户按下它。初始状态为Button"文本,并应更改为"Pressed"但是没有那样的事情发生。我做错了什么?
(ns examp.core
(:gen-class)
(:require [cljfx.api :as fx])
(:import [javafx.application Platform]))
(def *button-text (atom {:text "Button"}))
(def renderer
(fx/create-renderer))
(defn label-text[& args]
{:fx/type :label
:text "Press the button"})
(defn root [& args]
{:fx/type :stage
:showing true
:title "Cljfx"
:width 300
:height 300
:scene {:fx/type :scene
:root {:fx/type :v-box
:padding {:left 90 :top 19}
:spacing 10
:children [{:fx/type label-text}
{:fx/type :button
:min-width 50
:min-height 30
:text (:text @*button-text)
:on-action (fn [_]
(if (= (:text @*button-text) "Button")
(do
(swap! *button-text assoc :text "Pressed")
(println @*button-text)
(renderer {:fx/type root}))
(do
(swap! *button-text assoc :text "Button")
(println @*button-text)
(renderer {:fx/type root}))))}]}}})
(defn -main [& args]
(Platform/setImplicitExit true)
(renderer {:fx/type root}))
如果找不到特定于cljfx的解决方案,则始终可以直接使用JavaFX函数。我使用.setText
:
{:fx/type :button
:min-width 50
:min-height 30
:text "Click me!"
:on-action (fn [event]
(.setText (.getSource event) "Clicked!"))}
或者,如果您想在两个文本之间交替使用:
{:fx/type :button
:min-width 50
:min-height 30
:text "Click me!"
:on-action (fn [event]
(let [source (.getSource event)]
(if (= (.getText source) "Click me!")
(.setText source "Clicked!")
(.setText source "Click me!"))))}
所以我更仔细地检查了Cljfx代码的示例并找到了解决方案。这就是renderer的工作原理。
(ns examp.core
(:gen-class)
(:require [cljfx.api :as fx])
(:import [javafx.application Platform]))
(def text {:text "click me"})
(def renderer (fx/create-renderer))
(defn root [{:keys [text]}]
{:fx/type :stage
:showing true
:title "Window"
:scene {:fx/type :scene
:root {:fx/type :v-box
:children [{:fx/type :label
:text "press the button"}
{:fx/type :button
:min-width 100
:min-height 50
:text text
:on-action (fn [_]
(if (= text "click me")
(renderer
{:fx/type root
:text "clicked"})
(renderer
{:fx/type root
:text "click me"})))}]}}})
(defn -main [& args]
(Platform/setImplicitExit true)
(renderer {:fx/type root
:text (:text text)}))