Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure dialog box for file selection with filter for files' extensions

This is a continuous crawling for a lipster beginner on Clojure and Java. I have this code to select a file, but I would like to filter the files' extensions that I am looking for.

(import javax.swing.JFileChooser)
(defn tlt-get-file [ ]
       (let [ filechooser (JFileChooser. "C:/") 
              retval (.showOpenDialog filechooser nil) ]
          (if (= retval JFileChooser/APPROVE_OPTION)
             (do 
                (println (.getSelectedFile filechooser))
                (.getSelectedFile filechooser))
              "")))

Your help always much appreciated.

like image 287
logigolf Avatar asked Nov 17 '11 19:11

logigolf


2 Answers

(import '(javax.swing JFileChooser)
        '(javax.swing.filechooser FileNameExtensionFilter))
(defn tlt-get-file [ ]
       (let [ extFilter (FileNameExtensionFilter. "Text File" (into-array  ["txt"]))
              filechooser (JFileChooser. "C:/")
              dummy (.setFileFilter filechooser extFilter)
              retval (.showOpenDialog filechooser nil) ]
          (if (= retval JFileChooser/APPROVE_OPTION)
             (do 
                (println (.getSelectedFile filechooser))
                (.getSelectedFile filechooser))
              "")))
like image 168
BLUEPIXY Avatar answered Oct 27 '22 01:10

BLUEPIXY


You need to set the file filter, which you can do either by extending the FileFilter class, or using a built-in implementation like FileNameExtensionFilter. Note that the FNEF takes variable arguments in Java, which means that it takes an array in actual JVM bytecode. So something like

(FileNameExtensionFilter. 
 "Text files only"
 (into-array ["txt"]))

would be a simple, reasonable filter.

Or if you would rather do something more specialized, like only accept extensions which have a J in them, you can implement the filtering yourself. Sadly, Java chose to make this a 100% abstract class instead of an interface, so you can't use reify. In an ideal world you could write

(reify java.io.FileFilter
  (getDescription [this] "Java loves Js!")
  (accept [this f]
    (boolean (re-find #"\..*j[^.]*$" (.getName f)))))

but Java loves classes, so instead you need

(proxy [java.io.FileFilter] []
  (getDescription [] "Java loves Js!")
  (accept [f]
    (boolean (re-find #"\..*j[^.]*$" (.getName f)))))
like image 39
amalloy Avatar answered Oct 26 '22 23:10

amalloy