view src/clojure/contrib/test_contrib/miglayout/example.clj @ 10:ef7dbbd6452c

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