Clojure dialog box for selecting a file with a filter for file extensions

This is a continuous crawl for novice gubsters in Clojure and Java. I have this code to select a file, but I would like to filter the file extensions 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 is always greatly appreciated.

+6
source share
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)) ""))) 
+6
source

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

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

will be a simple, reasonable filter.

Or, if you prefer to do something more specialized, for example, only accept extensions that have J, you can implement filtering yourself. Unfortunately, Java chose to make this a 100% abstract class instead of an interface, so you cannot use reify. In an ideal world you can 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 to

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

Source: https://habr.com/ru/post/901744/


All Articles