Clojure で JPanel に画像を表示させ、ボタンで画像を切り替える

パネルを作成して画像を表示し、ボタンで画像を切り替える。

パネルに画像を表示するには、proxy を使って paint メソッドをオーバーライドする。

画像の再描画の際は、ref を使って保存しておいた BufferedImage から取り出して描く。

(import (javax.swing JFrame JPanel JButton BoxLayout)
        (javax.imageio ImageIO)
        (java.awt Graphics2D Color Dimension)
        (java.awt.image BufferedImage)
        (java.awt.event ActionListener)
        (java.io File))

(def *sample-image-path1* "/Users/hoge/sample1.jpg")
(def *sample-image-path2* "/Users/hoge/sample2.jpg")
(def *width* 400)
(def *height* 350)
(def *window-height* 400)
(def *img-buf*
  (ref {:buf (BufferedImage.
               *width*
               *height*
               BufferedImage/TYPE_BYTE_BINARY)}))

(defn read-image-from-file [path]
  (try
    (ImageIO/read (File. path))
    (catch Exception _ nil)))

(defn bufimage-to-graphics2d [bufimage]
  (let [g2d (.createGraphics bufimage)]
    g2d))

(defn render [g2d img]
  (.drawImage g2d img 0 0 nil))

(defn create-panel []
  (proxy [JPanel] []
    (paint [g2d]
      (do
        (.setColor g2d Color/WHITE)
        (.fillRect g2d 0 0 *width* *height*)
        (render g2d (@*img-buf* :buf))))))

(defn set-img-buf [img]
  (dosync (ref-set *img-buf* (assoc @*img-buf* :buf img))))

(defn set-image [panel img]
  (let [g2d (.getGraphics panel)]
    (do
      (.setColor g2d Color/WHITE)
      (.fillRect g2d 0 0 *width* *height*)
      (render g2d img)
      (set-img-buf img)
      (.dispose g2d))))

(def image-panel
  (create-panel))

(def button1
  (JButton. "Image1"))

(def button2
  (JButton. "Image2"))

(def layout-panel
  (JPanel.))

(def button-panel
  (JPanel.))

(def frame
  (JFrame.))

(do
  (map #(doto %1
          (.addActionListener
            (proxy [ActionListener] []
              (actionPerformed [evt]
                (do
                  (set-image %3 %2))))))
       [button1 button2]
       [(read-image-from-file *sample-image-path1*)
        (read-image-from-file *sample-image-path2*)]
       [image-panel image-panel]))

(doto image-panel
  (.setSize *width* *height*))

(doto button-panel
  (.setMaximumSize (Dimension. *width* (- *window-height* *height*)))
  (.add button1)
  (.add button2))

(doto layout-panel
  (.setLayout (BoxLayout. layout-panel BoxLayout/Y_AXIS))
  (.add image-panel)
  (.add button-panel))

(doto frame
  (.setDefaultCloseOperation
    javax.swing.WindowConstants/EXIT_ON_CLOSE)
  (.add layout-panel)
  (.setSize *width* *window-height*)
  (.setResizable false)
  (.setVisible true))

Clojure で画像を切り替える

プログラミングClojure
プログラミングClojure

posted with amazlet at 10.05.19
Stuart Halloway
オーム社
売り上げランキング: 8244
«
»