Example usage for javax.swing JFileChooser setFileFilter

List of usage examples for javax.swing JFileChooser setFileFilter

Introduction

In this page you can find the example usage for javax.swing JFileChooser setFileFilter.

Prototype

@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.")
public void setFileFilter(FileFilter filter) 

Source Link

Document

Sets the current file filter.

Usage

From source file:Main.java

public static void main(String[] args) {
    // Create a file filter to show only a directory or .doc files
    FileFilter filter = new FileFilter() {
        @Override/*from w w w. jav  a 2  s .c  o  m*/
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String fileName = f.getName().toLowerCase();
            if (fileName.endsWith(".doc")) {
                return true;
            }

            return false; // Reject any other files
        }

        @Override
        public String getDescription() {
            return "Word Document";
        }
    };

    // Set the file filter
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(filter);

    int returnValue = fileChooser.showDialog(null, "Attach");
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        // Process the file
    }

}

From source file:Main.java

public static void main(String[] args) {
    JFileChooser fileChooser = new JFileChooser(".");
    fileChooser.setControlButtonsAreShown(false);
    fileChooser.setFileFilter(new FolderFilter());
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.showOpenDialog(null);/*from   w w w  . j av  a2 s.c  o m*/
}

From source file:FileFilterDemo.java

public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
        }/*w  w  w  .  ja v  a2s  .co  m*/

        public String getDescription() {
            return "GIF Images";
        }
    });

    int r = chooser.showOpenDialog(new JFrame());
    if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getName();
        System.out.println(name);
    }
}

From source file:Main.java

public static void main(String[] a) {
    JFileChooser fileChooser = new JFileChooser(".");
    FileFilter filter1 = new ExtensionFileFilter("JPG and JPEG", new String[] { "JPG", "JPEG" });
    fileChooser.setFileFilter(filter1);
    int status = fileChooser.showOpenDialog(null);
    if (status == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        System.out.println(selectedFile.getParent());
        System.out.println(selectedFile.getName());
    } else if (status == JFileChooser.CANCEL_OPTION) {
        System.out.println(JFileChooser.CANCEL_OPTION);
    }/*from w  w  w. j a v  a  2 s.  c om*/
}

From source file:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();

    f.setSize(300, 500);//  ww  w .j  a v  a 2 s.c  om
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel pan = new JPanel(new GridLayout(1, 1));
    XmlJTree myTree = new XmlJTree(null);
    f.add(new JScrollPane(myTree));
    JButton button = new JButton("Choose file");
    button.addActionListener(e -> {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            myTree.setPath(chooser.getSelectedFile().getAbsolutePath());
        }
    });
    pan.add(button);
    f.add(pan, BorderLayout.SOUTH);
    f.setVisible(true);
}

From source file:AudioFilter.java

public static void main(String[] args) {
    AudioFilter audioFilter = new AudioFilter();

    JFileChooser jfc = new JFileChooser();

    jfc.setDialogTitle("Open File");
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setCurrentDirectory(new File("."));
    jfc.setFileFilter(audioFilter);
    int result = jfc.showOpenDialog(null);

    if (result == JFileChooser.CANCEL_OPTION) {
        System.out.println("cancel");
    } else if (result == JFileChooser.APPROVE_OPTION) {
        File fFile = jfc.getSelectedFile();
        String filestr = fFile.getAbsolutePath();

        System.out.println(filestr);
    }// ww  w  .  j av  a 2 s . c om
}

From source file:kindleclippings.word.QuizletSync.java

public static void main(String[] args) throws IOException, JSONException, URISyntaxException,
        InterruptedException, BackingStoreException, BadLocationException {

    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt"));
    fc.setMultiSelectionEnabled(true);/*  www  .jav  a  2 s . c  om*/
    int result = fc.showOpenDialog(null);
    if (result != JFileChooser.APPROVE_OPTION) {
        return;
    }
    File[] clf = fc.getSelectedFiles();
    if (clf == null || clf.length == 0)
        return;

    ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100);
    progress.setMillisToPopup(0);
    progress.setMillisToDecideToPopup(0);
    progress.setProgress(0);
    try {

        progress.setNote("checking Quizlet account");
        progress.setProgress(5);

        Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs();

        QuizletAPI api = new QuizletAPI(prefs.get("access_token", null));

        Collection<TermSet> sets = null;
        try {
            progress.setNote("checking Quizlet library");
            progress.setProgress(10);
            sets = api.getSets(prefs.get("user_id", null));
        } catch (IOException e) {
            if (e.toString().contains("401")) {
                // Not Authorized => Token has been revoked
                kindleclippings.quizlet.QuizletSync.clearPrefs();
                prefs = kindleclippings.quizlet.QuizletSync.getPrefs();
                api = new QuizletAPI(prefs.get("access_token", null));
                sets = api.getSets(prefs.get("user_id", null));
            } else {
                throw e;
            }
        }

        progress.setProgress(15);
        progress.setMaximum(15 + clf.length * 10);
        progress.setNote("uploading new notes");

        int pro = 15;

        int addedSets = 0;
        int updatedTerms = 0;
        int updatedSets = 0;

        for (File f : clf) {
            progress.setProgress(pro);
            List<Clipping> clippings = readClippingsFile(f);

            if (clippings == null) {
                pro += 10;
                continue;
            }

            if (clippings.isEmpty()) {
                pro += 10;
                continue;
            }

            if (clippings.size() < 2) {
                pro += 10;
                continue;
            }

            String book = clippings.get(0).getBook();
            progress.setNote(book);

            TermSet termSet = null;
            String x = book.toLowerCase().replaceAll("\\W", "");

            for (TermSet t : sets) {
                if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) {
                    termSet = t;
                    break;
                }
            }

            if (termSet == null) {

                addSet(api, book, clippings);
                addedSets++;
                pro += 10;
                continue;
            }

            // compare against existing terms
            boolean hasUpdated = false;
            for (Clipping cl : clippings) {
                if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) {
                    kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl);
                    updatedTerms++;
                    hasUpdated = true;
                }
            }

            pro += 10;

            if (hasUpdated)
                updatedSets++;

        }

        if (updatedTerms == 0 && addedSets == 0) {
            JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync",
                    JOptionPane.OK_OPTION);
        } else {
            if (addedSets > 0) {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets",
                                addedSets, updatedSets, updatedTerms),
                        "QuizletSync", JOptionPane.OK_OPTION);
            } else {
                JOptionPane.showMessageDialog(null,
                        String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets),
                        "QuizletSync", JOptionPane.OK_OPTION);
            }
        }
    } finally {
        progress.close();
    }

    System.exit(0);
}

From source file:jsonbrowse.JsonBrowse.java

/**
 * @param args the command line arguments
 *///  w ww  . ja va2s  . co m
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JsonBrowse.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    String fileName;

    // Get name of JSON file
    Path jsonFilePath;
    if (args.length < 1) {

        JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
        fc.setDialogTitle("Select JSON file...");
        fc.setFileFilter(new FileNameExtensionFilter("JSON files (*.json/*.txt)", "json", "txt"));
        if ((fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)) {
            jsonFilePath = fc.getSelectedFile().toPath().toAbsolutePath();
        } else {
            return;
        }
    } else {
        Path path = Paths.get(args[0]);
        if (!path.isAbsolute())
            jsonFilePath = Paths.get(System.getProperty("user.dir")).resolve(path);
        else
            jsonFilePath = path;
    }

    // Run app

    try {
        JsonBrowse app = new JsonBrowse(jsonFilePath);
        app.setVisible(true);
    } catch (FileNotFoundException ex) {
        System.out.println("Input file '" + jsonFilePath + "' not found.");
        System.exit(1);
    } catch (IOException ex) {
        System.out.println("Error reading from file '" + jsonFilePath + "'.");
        System.exit(1);
    } catch (InterruptedException ex) {
        Logger.getLogger(JsonBrowse.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.dakror.jagui.parser.NGuiParser.java

public static void main(String[] args) {
    try {//from  ww w .j  a v a2 s  . com
        DIR.mkdirs();
        if (!new File(DIR, "convert.exe").exists())
            Helper.copyInputStream(NGuiParser.class.getResourceAsStream("/res/convert.exe"),
                    new FileOutputStream(new File(DIR, "convert.exe")));

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        JFileChooser jfc = new JFileChooser(
                new File(NGuiParser.class.getProtectionDomain().getCodeSource().getLocation().toURI()));
        jfc.setMultiSelectionEnabled(false);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new FileNameExtensionFilter("Unity ngui Gui-Skin (*.guiskin)", "guiskin"));

        if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            p("Collecting GUIDs, Converting Resources");
            HashMap<String, File> guids = collectGUIDs(jfc.getCurrentDirectory());

            p("Parsing Guiskin file");
            String s = Helper.getFileContent(jfc.getSelectedFile());
            String[] lines = s.split("\n");
            ArrayList<String> l = new ArrayList<>(Arrays.asList(lines));
            String string = "";
            for (int i = 0; i < l.size(); i++)
                if (!l.get(i).startsWith("%") && !l.get(i).startsWith("---"))
                    string += l.get(i) + "\n";

            Yaml yaml = new Yaml();
            for (Iterator<Object> iter = yaml.loadAll(string).iterator(); iter.hasNext();) {
                JSONObject o = new JSONObject((Map<?, ?>) iter.next());
                p("Cconverting Guiskin");
                replaceGuidDeep(o, guids, jfc.getSelectedFile());
                p("Writing converted file");
                Helper.setFileContent(new File(jfc.getSelectedFile().getParentFile(),
                        jfc.getSelectedFile().getName() + ".json"), o.toString(4));
                p("DONE");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:kenh.xscript.ScriptUtils.java

public static void main(String[] args) {
    String file = null;/*from   www.  jav  a2 s  . co  m*/

    for (String arg : args) {
        if (StringUtils.startsWithAny(StringUtils.lowerCase(arg), "-f:", "-file:")) {
            file = StringUtils.substringAfter(arg, ":");
        }
    }

    Element e = null;
    try {
        if (StringUtils.isBlank(file)) {

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("xScript");
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    } else if (f.isFile() && StringUtils.endsWithIgnoreCase(f.getName(), ".xml")) {
                        return true;
                    }
                    return false;
                }

                public String getDescription() {
                    return "xScript (*.xml)";
                }
            });

            int returnVal = chooser.showOpenDialog(null);
            chooser.requestFocus();

            if (returnVal == JFileChooser.CANCEL_OPTION)
                return;

            File f = chooser.getSelectedFile();

            e = getInstance(f, null);
        } else {
            e = getInstance(new File(file), null);
        }
        //debug(e);
        //System.out.println("----------------------");

        int result = e.invoke();
        if (result == Element.EXCEPTION) {
            Object obj = e.getEnvironment().getVariable(Constant.VARIABLE_EXCEPTION);
            if (obj != null && obj instanceof Throwable) {
                System.err.println();
                ((Throwable) obj).printStackTrace();

            } else {
                System.err.println();
                System.err.println("Unknown EXCEPTION is thrown.");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();

        System.err.println();

        if (ex instanceof UnsupportedScriptException) {
            UnsupportedScriptException ex_ = (UnsupportedScriptException) ex;
            if (ex_.getElement() != null) {
                debug(ex_.getElement(), System.err);
            }
        }
    } finally {
        if (e != null)
            e.getEnvironment().callback();
    }
}