rlm@10
|
1 ;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
|
rlm@10
|
2 ;; distribution terms for this software are covered by the Eclipse Public
|
rlm@10
|
3 ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
|
rlm@10
|
4 ;; be found in the file epl-v10.html at the root of this distribution. By
|
rlm@10
|
5 ;; using this software in any fashion, you are agreeing to be bound by the
|
rlm@10
|
6 ;; terms of this license. You must not remove this notice, or any other,
|
rlm@10
|
7 ;; from this software.
|
rlm@10
|
8 ;;
|
rlm@10
|
9 ;; clojure.contrib.miglayout.example
|
rlm@10
|
10 ;;
|
rlm@10
|
11 ;; A temperature converter using miglayout. Demonstrates accessing
|
rlm@10
|
12 ;; components by their id constraint.
|
rlm@10
|
13 ;;
|
rlm@10
|
14 ;; scgilardi (gmail)
|
rlm@10
|
15 ;; Created 31 May 2009
|
rlm@10
|
16
|
rlm@10
|
17 (ns clojure.contrib.miglayout.example
|
rlm@10
|
18 (:import (javax.swing JButton JFrame JLabel JPanel JTextField
|
rlm@10
|
19 SwingUtilities))
|
rlm@10
|
20 (:use (clojure.contrib
|
rlm@10
|
21 [miglayout :only (miglayout components)]
|
rlm@10
|
22 [swing-utils :only (add-key-typed-listener)])))
|
rlm@10
|
23
|
rlm@10
|
24 (defn fahrenheit
|
rlm@10
|
25 "Converts a Celsius temperature to Fahrenheit. Input and output are
|
rlm@10
|
26 strings. Returns \"input?\" if the input can't be parsed as a Double."
|
rlm@10
|
27 [celsius]
|
rlm@10
|
28 (try
|
rlm@10
|
29 (format "%.2f" (+ 32 (* 1.8 (Double/parseDouble celsius))))
|
rlm@10
|
30 (catch NumberFormatException _ "input?")))
|
rlm@10
|
31
|
rlm@10
|
32 (defn- handle-key
|
rlm@10
|
33 "Clears output on most keys, shows conversion on \"Enter\""
|
rlm@10
|
34 [event out]
|
rlm@10
|
35 (.setText out
|
rlm@10
|
36 (if (= (.getKeyChar event) \newline)
|
rlm@10
|
37 (fahrenheit (-> event .getComponent .getText))
|
rlm@10
|
38 "")))
|
rlm@10
|
39
|
rlm@10
|
40 (defn converter-ui
|
rlm@10
|
41 "Lays out and shows a Temperature Converter UI"
|
rlm@10
|
42 []
|
rlm@10
|
43 (let [panel
|
rlm@10
|
44 (miglayout (JPanel.)
|
rlm@10
|
45 (JTextField. 6) {:id :input}
|
rlm@10
|
46 (JLabel. "\u00b0Celsius") :wrap
|
rlm@10
|
47 (JLabel.) {:id :output}
|
rlm@10
|
48 (JLabel. "\u00b0Fahrenheit"))
|
rlm@10
|
49 {:keys [input output]} (components panel)]
|
rlm@10
|
50 (add-key-typed-listener input handle-key output)
|
rlm@10
|
51 (doto (JFrame. "Temperature Converter")
|
rlm@10
|
52 (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
|
rlm@10
|
53 (.add panel)
|
rlm@10
|
54 (.pack)
|
rlm@10
|
55 (.setVisible true))))
|
rlm@10
|
56
|
rlm@10
|
57 (defn main
|
rlm@10
|
58 "Invokes converter-ui in the AWT Event thread"
|
rlm@10
|
59 []
|
rlm@10
|
60 (SwingUtilities/invokeLater converter-ui))
|