(ns swingproject.core
(:gen-class)
(:import
[javax.swing SwingUtilities JFrame JTextField JPanel JLabel]
[java.awt FlowLayout]
[java.awt.event ActionListener]))
(defn convert-temp [celsius fahrenheit to-celsius]
(if to-celsius
(let [f (.getText fahrenheit)
f-as-int (Integer/parseInt f)
c (* 5/9 (- f-as-int 32))]
(SwingUtilities/invokeLater #(.setText celsius (str (float c)))))
(let [c (.getText celsius)
c-as-int (Integer/parseInt c)
f (+ 32 (* 9/5 c-as-int))]
(SwingUtilities/invokeLater #(.setText fahrenheit (str (float f)))))))
(defn create-and-show-gui
[]
(let [my-frame (doto (JFrame. "My Frame")
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setLocationRelativeTo nil))
celsius-panel (JPanel. (FlowLayout.))
fahrenheit-panel (JPanel. (FlowLayout.))
celsius (JTextField. "0" 10)
fahrenheit (JTextField. "32" 10)
content-pane (doto (.getContentPane my-frame)
(.setLayout (FlowLayout.)))]
(.addActionListener celsius
(reify ActionListener
(actionPerformed [this e] (convert-temp celsius fahrenheit false))))
(.addActionListener fahrenheit
(reify ActionListener
(actionPerformed [this e] (convert-temp celsius fahrenheit true))))
(.add celsius-panel (JLabel. "Celsius"))
(.add celsius-panel celsius)
(.add fahrenheit-panel (JLabel. "Fahrenheit"))
(.add fahrenheit-panel fahrenheit)
(.add content-pane celsius-panel)
(.add content-pane fahrenheit-panel)
(.pack my-frame)
(.setSize my-frame 300 200)
(.setVisible my-frame true)))
(defn -main
"entry point for app"
[& args]
(SwingUtilities/invokeLater create-and-show-gui))