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:org.stanwood.nwn2.gui.MainWindow.java

private void addNewGUIFile() {
    File dir = settings.getGUIXMLBrowseDirLastDir(
            new File(settings.getNWN2Dir(NWN2GuiSettings.DEFAULT_NWN2_DIR), "UI" + File.separator + "default"));
    JFileChooser fc = new JFileChooser(dir);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setFileFilter(new FileFilter() {
        @Override// w  w  w.j  a  v a2s.  co m
        public String getDescription() {
            return "NWN2 GUI (*.xml)";
        }

        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
        }
    });
    fc.showOpenDialog(MainWindow.this);
    File selFile = fc.getSelectedFile();
    if (selFile != null) {
        guiFileListModel.addElement(selFile);
        guiFileList.setSelectedIndex(guiFileListModel.getSize() - 1);
        settings.setGUIXMLBrowseDirLastDir(selFile.getParentFile());
        updateEnabledState();
        saveChanges();
    }
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openJFileChooser(int mode, String dialogTitle, boolean open, String filename,
        FileNameExtensionFilter filter) {
    JFileChooser fileChooser;
    // are we forced to open the legacy file chooser?
    if ("true".equals(System.getProperty("tmm.legacy.filechooser"))) {
        fileChooser = new JFileChooser();
    } else {//from   w w w.  ja  va  2s  .  c o  m
        fileChooser = new NativeFileChooser();
    }

    fileChooser.setFileSelectionMode(mode);
    if (lastDir != null) {
        fileChooser.setCurrentDirectory(lastDir.toFile());
    }
    fileChooser.setDialogTitle(dialogTitle);

    int result = -1;
    if (open) {
        result = fileChooser.showOpenDialog(MainWindow.getFrame());
    } else {
        if (StringUtils.isNotBlank(filename)) {
            fileChooser.setSelectedFile(new File(filename));
            fileChooser.setFileFilter(filter);
        }
        result = fileChooser.showSaveDialog(MainWindow.getFrame());
    }

    if (result == JFileChooser.APPROVE_OPTION) {
        if (mode == JFileChooser.DIRECTORIES_ONLY) {
            lastDir = fileChooser.getSelectedFile().toPath();
        } else {
            lastDir = fileChooser.getSelectedFile().getParentFile().toPath();
        }
        return fileChooser.getSelectedFile().toPath();
    }

    return null;
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename./*from   w ww  . ja  va 2 s .  co  m*/
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Action entry points./*from  w w w .ja va2s . c o m*/
 * <p>
 * All action entry points named with +ActionPerformed().
 */
public void onFileOpen() {
    final JFileChooser fc = new JFileChooser();
    File filePath = RuntimePreferences.getUserHome();
    fc.setCurrentDirectory(filePath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Project File(.tmpx)", "tmpx");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    final int returnVal = fc.showOpenDialog(parent);
    filePath = fc.getCurrentDirectory();
    RuntimePreferences.setUserHome(filePath);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        filePath = fc.getSelectedFile();

        if (filePath.getName().endsWith(".tmpx") && filePath.exists()) {
            try {
                final FileInputStream fr = new FileInputStream(filePath);
                fr.close();
                onOpenFile(filePath);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"),
                        getString("MSG.ERROR"), JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"), getString("MSG.ERROR"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.wso2.carbon.cluster.ui.ClusterWizard.java

private void btnZipFileSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZipFileSelectActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Zip File", "zip");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(getParent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        zipAbsFilePath = chooser.getSelectedFile().getAbsolutePath();
        txtZipFilePath.setText(zipAbsFilePath);
        zipFileName = FilenameUtils.removeExtension(chooser.getSelectedFile().getName());
    }/*w w w .j av  a  2 s. c om*/
}

From source file:org.yccheok.jstock.gui.Utils.java

public static FileEx promptSavePortfolioCSVAndExcelJFileChooser(final String suggestedFileName) {
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final JFileChooser chooser = new JFileChooser(jStockOptions.getLastFileIODirectory());
    final FileNameExtensionFilter csvFilter = new FileNameExtensionFilter("CSV Documents (*.csv)", "csv");
    final FileNameExtensionFilter xlsFilter = new FileNameExtensionFilter("Microsoft Excel (*.xls)", "xls");
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.addChoosableFileFilter(csvFilter);
    chooser.addChoosableFileFilter(xlsFilter);

    final org.yccheok.jstock.gui.file.PortfolioSelectionJPanel portfolioSelectionJPanel = new org.yccheok.jstock.gui.file.PortfolioSelectionJPanel();
    chooser.setAccessory(portfolioSelectionJPanel);
    chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() {

        @Override/*from  w  ww  .  j  a va 2s . c  om*/
        public void propertyChange(PropertyChangeEvent evt) {
            final boolean flag = ((FileNameExtensionFilter) evt.getNewValue()).equals(csvFilter);
            portfolioSelectionJPanel.setEnabled(flag);
            chooser.setSelectedFile(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())
                    ? new File(portfolioSelectionJPanel.getSuggestedFileName())
                    : new File(suggestedFileName));
        }

    });
    portfolioSelectionJPanel.addJRadioButtonsActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            chooser.setSelectedFile(new File(portfolioSelectionJPanel.getSuggestedFileName()));
        }

    });
    final java.util.Map<String, FileNameExtensionFilter> map = new HashMap<String, FileNameExtensionFilter>();
    map.put(csvFilter.getDescription(), csvFilter);
    map.put(xlsFilter.getDescription(), xlsFilter);

    final FileNameExtensionFilter filter = map.get(jStockOptions.getLastSavedFileNameExtensionDescription());
    if (filter != null) {
        chooser.setFileFilter(filter);
    }

    // Only enable portfolioSelectionJPanel, if CSV is being selected.
    portfolioSelectionJPanel
            .setEnabled(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription()));
    chooser.setSelectedFile(chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())
            ? new File(portfolioSelectionJPanel.getSuggestedFileName())
            : new File(suggestedFileName));

    while (true) {
        final int returnVal = chooser.showSaveDialog(JStock.instance());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        File file = chooser.getSelectedFile();
        if (file == null) {
            return null;
        }

        // Ensure the saved file is in correct extension. If user provide correct
        // file extension explicitly, leave it as is. If not, mutate the filename.
        final String extension = Utils.getFileExtension(file);
        if (extension.equals("csv") == false && extension.equals("xls") == false) {
            if (chooser.getFileFilter().getDescription().equals(csvFilter.getDescription())) {
                file = new File(file.getAbsolutePath() + ".csv");
            } else if (chooser.getFileFilter().getDescription().equals(xlsFilter.getDescription())) {
                file = new File(file.getAbsolutePath() + ".xls");
            } else {
                // Impossible.
                return null;
            }
        }

        if (file.exists()) {
            final String output = MessageFormat
                    .format(MessagesBundle.getString("question_message_replace_old_template"), file.getName());

            final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                    MessagesBundle.getString("question_title_replace_old"),
                    javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
            if (result != javax.swing.JOptionPane.YES_OPTION) {
                continue;
            }
        }

        final String parent = chooser.getSelectedFile().getParent();
        if (parent != null) {
            jStockOptions.setLastFileIODirectory(parent);
        }

        if (Utils.getFileExtension(file).equals("csv")) {
            jStockOptions.setLastFileNameExtensionDescription(csvFilter.getDescription());
        } else if (Utils.getFileExtension(file).equals("xls")) {
            jStockOptions.setLastFileNameExtensionDescription(xlsFilter.getDescription());
        } else {
            // Impossible.
            return null;
        }

        return new FileEx(file, portfolioSelectionJPanel.getType());
    }
}

From source file:org.yccheok.jstock.gui.Utils.java

private static File promptOpenJFileChooser(FileNameExtensionFilter... fileNameExtensionFilters) {
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final JFileChooser chooser = new JFileChooser(jStockOptions.getLastFileIODirectory());
    chooser.setAcceptAllFileFilterUsed(false);
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        chooser.addChoosableFileFilter(fileNameExtensionFilter);
    }/*from w w  w .ja v a 2s. c  o  m*/
    final java.util.Map<String, FileNameExtensionFilter> map = new HashMap<String, FileNameExtensionFilter>();
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        map.put(fileNameExtensionFilter.getDescription(), fileNameExtensionFilter);
    }
    final FileNameExtensionFilter filter = map.get(jStockOptions.getLastSavedFileNameExtensionDescription());
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    int returnVal = chooser.showOpenDialog(JStock.instance());

    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return null;
    }

    File file = chooser.getSelectedFile();
    if (file == null || !file.exists()) {
        return null;
    }
    final String parent = chooser.getSelectedFile().getParent();
    if (parent != null) {
        jStockOptions.setLastFileIODirectory(parent);
    }
    final String extension = Utils.getFileExtension(file);
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        final String[] extensions = fileNameExtensionFilter.getExtensions();
        if (extensions.length <= 0) {
            continue;
        }
        if (extension.equals(extensions[0])) {
            jStockOptions.setLastFileNameExtensionDescription(fileNameExtensionFilter.getDescription());
            return file;
        }
    }
    return null;
}

From source file:org.yccheok.jstock.gui.Utils.java

private static File promptSaveJFileChooser(String suggestedFileName,
        FileNameExtensionFilter... fileNameExtensionFilters) {
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final JFileChooser chooser = new JFileChooser(jStockOptions.getLastFileIODirectory());
    chooser.setAcceptAllFileFilterUsed(false);
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        chooser.addChoosableFileFilter(fileNameExtensionFilter);
    }/*from   www.  ja  va 2  s  . c o  m*/
    chooser.setSelectedFile(new File(suggestedFileName));
    final java.util.Map<String, FileNameExtensionFilter> map = new HashMap<String, FileNameExtensionFilter>();
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        map.put(fileNameExtensionFilter.getDescription(), fileNameExtensionFilter);
    }
    final FileNameExtensionFilter filter = map.get(jStockOptions.getLastSavedFileNameExtensionDescription());
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    while (true) {
        final int returnVal = chooser.showSaveDialog(JStock.instance());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        File file = chooser.getSelectedFile();
        if (file == null) {
            return null;
        }
        // Ensure the saved file is in correct extension. If user provide correct
        // file extension explicitly, leave it as is. If not, mutate the filename.
        final String extension = Utils.getFileExtension(file);
        boolean found = false;
        root: for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
            String[] extensions = fileNameExtensionFilter.getExtensions();
            for (String e : extensions) {
                if (e.equals(extension)) {
                    found = true;
                    break root;
                }
            }
        }
        if (!found) {
            for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
                String[] extensions = fileNameExtensionFilter.getExtensions();
                if (extensions.length <= 0) {
                    continue;
                }
                final String e = extensions[0];
                if (chooser.getFileFilter().getDescription().equals(fileNameExtensionFilter.getDescription())) {
                    if (e.startsWith(".")) {
                        file = new File(file.getAbsolutePath() + e);
                    } else {
                        file = new File(file.getAbsolutePath() + "." + e);
                    }
                    break;
                }
            }
        }
        if (file.exists()) {
            final String output = MessageFormat
                    .format(MessagesBundle.getString("question_message_replace_old_template"), file.getName());

            final int result = javax.swing.JOptionPane.showConfirmDialog(JStock.instance(), output,
                    MessagesBundle.getString("question_title_replace_old"),
                    javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);
            if (result != javax.swing.JOptionPane.YES_OPTION) {
                continue;
            }
        }

        final String parent = chooser.getSelectedFile().getParent();
        if (parent != null) {
            jStockOptions.setLastFileIODirectory(parent);
        }
        final String e = Utils.getFileExtension(file);
        for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
            String[] extensions = fileNameExtensionFilter.getExtensions();
            if (extensions.length <= 0) {
                continue;
            }
            if (e.equals(extensions[0])) {
                jStockOptions.setLastFileNameExtensionDescription(fileNameExtensionFilter.getDescription());
                break;
            }
        }
        return file;
    }
}

From source file:org.zaproxy.zap.extension.ascan.PolicyManagerDialog.java

private JButton getImportButton() {
    if (this.importButton == null) {
        this.importButton = new JButton(Constant.messages.getString("ascan.policymgr.button.import"));
        this.importButton.addActionListener(new ActionListener() {
            @Override/*from  w w  w  .  j  a va  2 s .  com*/
            public void actionPerformed(ActionEvent e) {
                // Default to ZAP home dir - we dont want to import/export to the policy dir
                JFileChooser chooser = new JFileChooser(Constant.getZapHome());
                chooser.setFileFilter(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        if (file.isDirectory()) {
                            return true;
                        } else if (file.isFile() && file.getName().endsWith(".policy")) {
                            return true;
                        }
                        return false;
                    }

                    @Override
                    public String getDescription() {
                        return Constant.messages.getString("file.format.zap.policy");
                    }
                });
                File file = null;
                int rc = chooser.showOpenDialog(View.getSingleton().getMainFrame());
                if (rc == JFileChooser.APPROVE_OPTION) {
                    file = chooser.getSelectedFile();
                    if (file == null) {
                        return;
                    }
                    try {
                        extension.getPolicyManager().importPolicy(file);
                        policyNamesChanged();
                    } catch (ConfigurationException | IOException e1) {
                        logger.error(e1.getMessage(), e1);
                        View.getSingleton()
                                .showWarningDialog(Constant.messages.getString("ascan.policy.load.error"));
                    }
                }
            }
        });
    }
    return this.importButton;
}

From source file:org.zaproxy.zap.extension.ascan.PolicyManagerDialog.java

private JButton getExportButton() {
    if (this.exportButton == null) {
        this.exportButton = new JButton(Constant.messages.getString("ascan.policymgr.button.export"));
        this.exportButton.setEnabled(false);
        this.exportButton.addActionListener(new ActionListener() {
            @Override//from  w w  w  .j a va 2 s . c  om
            public void actionPerformed(ActionEvent e) {
                String name = (String) getParamsModel().getValueAt(getParamsTable().getSelectedRow(), 0);
                if (name != null) {
                    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
                    File file = new File(Constant.getZapHome(), name + PolicyManager.POLICY_EXTENSION);
                    chooser.setSelectedFile(file);

                    chooser.setFileFilter(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            if (file.isDirectory()) {
                                return true;
                            } else if (file.isFile() && file.getName().endsWith(".policy")) {
                                return true;
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Constant.messages.getString("file.format.zap.policy");
                        }
                    });
                    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
                    if (rc == JFileChooser.APPROVE_OPTION) {
                        file = chooser.getSelectedFile();
                        if (file == null) {
                            return;
                        }
                        try {
                            ScanPolicy policy = extension.getPolicyManager().getPolicy(name);
                            if (policy != null) {
                                extension.getPolicyManager().exportPolicy(policy, file);
                            }
                        } catch (ConfigurationException e1) {
                            logger.error(e1.getMessage(), e1);
                            View.getSingleton()
                                    .showWarningDialog(Constant.messages.getString("ascan.policy.load.error"));
                        }
                    }
                }
            }
        });
    }
    return this.exportButton;
}