Example usage for javax.swing JFileChooser getFileFilter

List of usage examples for javax.swing JFileChooser getFileFilter

Introduction

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

Prototype

public FileFilter getFileFilter() 

Source Link

Document

Returns the currently selected file filter.

Usage

From source file:Main.java

public static void main(String[] a) {
    JFrame frame = new JFrame("JFileChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JFileChooser fileChooser = new JFileChooser(".");

    FileFilter f = fileChooser.getFileFilter();
    frame.add(fileChooser, BorderLayout.CENTER);

    frame.pack();/*  w w  w.j  a  v  a2 s .  c om*/
    frame.setVisible(true);
}

From source file:net.sf.jabref.importer.ImportFormats.java

/**
 * Create an AbstractAction for performing an Import operation.
 * @param frame The JabRefFrame of this JabRef instance.
 * @param openInNew Indicate whether the action should open into a new database or
 *  into the currently open one.//w  w  w.  jav a2  s.c  om
 * @return The action.
 */
public static AbstractAction getImportAction(JabRefFrame frame, boolean openInNew) {

    class ImportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;
        private final boolean openInNew;

        public ImportAction(JabRefFrame frame, boolean openInNew) {
            this.frame = frame;
            this.openInNew = openInNew;

            putValue(Action.NAME, openInNew ? Localization.menuTitle("Import into new database")
                    : Localization.menuTitle("Import into current database"));
            putValue(Action.ACCELERATOR_KEY,
                    openInNew ? Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_NEW_DATABASE)
                            : Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_CURRENT_DATABASE));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = createImportFileChooser(
                    Globals.prefs.get(JabRefPreferences.IMPORT_WORKING_DIRECTORY));
            int result = fileChooser.showOpenDialog(frame);

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

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

            FileFilter ff = fileChooser.getFileFilter();
            ImportFormat format = null;
            if (ff instanceof ImportFileFilter) {
                format = ((ImportFileFilter) ff).getImportFormat();
            }

            try {
                if (!file.exists()) {
                    // Warn that the file doesn't exists:
                    JOptionPane.showMessageDialog(frame,
                            Localization.lang("File not found") + ": '" + file.getName() + "'.",
                            Localization.lang("Import"), JOptionPane.ERROR_MESSAGE);
                    return;
                }
                ImportMenuItem imi = new ImportMenuItem(frame, openInNew, format);
                imi.automatedImport(Collections.singletonList(file.getAbsolutePath()));

                // Make sure we remember which filter was used, to set the default
                // for next time:
                if (format == null) {
                    Globals.prefs.put(JabRefPreferences.LAST_USED_IMPORT, "__all");
                } else {
                    Globals.prefs.put(JabRefPreferences.LAST_USED_IMPORT, format.getFormatName());
                }
                Globals.prefs.put(JabRefPreferences.IMPORT_WORKING_DIRECTORY, file.getParent());
            } catch (Exception ex) {
                LOGGER.warn("Problem with import format", ex);
            }

        }
    }

    return new ImportAction(frame, openInNew);
}

From source file:net.sf.jabref.exporter.ExportFormats.java

/**
 * Create an AbstractAction for performing an export operation.
 *
 * @param frame/*from w  w  w .j  a  va 2  s .c  o m*/
 *            The JabRefFrame of this JabRef instance.
 * @param selectedOnly
 *            true indicates that only selected entries should be exported,
 *            false indicates that all entries should be exported.
 * @return The action.
 */
public static AbstractAction getExportAction(JabRefFrame frame, boolean selectedOnly) {

    class ExportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;

        private final boolean selectedOnly;

        public ExportAction(JabRefFrame frame, boolean selectedOnly) {
            this.frame = frame;
            this.selectedOnly = selectedOnly;
            putValue(Action.NAME, selectedOnly ? Localization.menuTitle("Export selected entries")
                    : Localization.menuTitle("Export"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ExportFormats.initAllExports();
            JFileChooser fc = ExportFormats
                    .createExportFileChooser(Globals.prefs.get(JabRefPreferences.EXPORT_WORKING_DIRECTORY));
            fc.showSaveDialog(frame);
            File file = fc.getSelectedFile();
            if (file == null) {
                return;
            }
            FileFilter ff = fc.getFileFilter();
            if (ff instanceof ExportFileFilter) {

                ExportFileFilter eff = (ExportFileFilter) ff;
                String path = file.getPath();
                if (!path.endsWith(eff.getExtension())) {
                    path = path + eff.getExtension();
                }
                file = new File(path);
                if (file.exists()) {
                    // Warn that the file exists:
                    if (JOptionPane.showConfirmDialog(frame,
                            Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                            Localization.lang("Export"),
                            JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
                        return;
                    }
                }
                final IExportFormat format = eff.getExportFormat();
                List<BibEntry> entries;
                if (selectedOnly) {
                    // Selected entries
                    entries = frame.getCurrentBasePanel().getSelectedEntries();
                } else {
                    // All entries
                    entries = frame.getCurrentBasePanel().getDatabase().getEntries();
                }

                // Set the global variable for this database's file directory before exporting,
                // so formatters can resolve linked files correctly.
                // (This is an ugly hack!)
                Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext()
                        .getFileDirectory();

                // Make sure we remember which filter was used, to set
                // the default for next time:
                Globals.prefs.put(JabRefPreferences.LAST_USED_EXPORT, format.getConsoleName());
                Globals.prefs.put(JabRefPreferences.EXPORT_WORKING_DIRECTORY, file.getParent());

                final File finFile = file;
                final List<BibEntry> finEntries = entries;
                AbstractWorker exportWorker = new AbstractWorker() {

                    String errorMessage;

                    @Override
                    public void run() {
                        try {
                            format.performExport(frame.getCurrentBasePanel().getBibDatabaseContext(),
                                    finFile.getPath(), frame.getCurrentBasePanel().getEncoding(), finEntries);
                        } catch (Exception ex) {
                            LOGGER.warn("Problem exporting", ex);
                            if (ex.getMessage() == null) {
                                errorMessage = ex.toString();
                            } else {
                                errorMessage = ex.getMessage();
                            }
                        }
                    }

                    @Override
                    public void update() {
                        // No error message. Report success:
                        if (errorMessage == null) {
                            frame.output(Localization.lang("%0 export successful", format.getDisplayName()));
                        }
                        // ... or show an error dialog:
                        else {
                            frame.output(Localization.lang("Could not save file.") + " - " + errorMessage);
                            // Need to warn the user that saving failed!
                            JOptionPane.showMessageDialog(frame,
                                    Localization.lang("Could not save file.") + "\n" + errorMessage,
                                    Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
                        }
                    }
                };

                // Run the export action in a background thread:
                exportWorker.getWorker().run();
                // Run the update method:
                exportWorker.update();
            }
        }
    }

    return new ExportAction(frame, selectedOnly);
}

From source file:org.pgptool.gui.ui.tools.browsefs.SaveFileChooserDialog.java

private String enforceExtension(String filePathName, JFileChooser ofd) {
    FileFilter fileExtFilter = ofd.getFileFilter();
    if (fileExtFilter == ofd.getAcceptAllFileFilter()) {
        return filePathName;
    }/*ww w. j av  a2  s  .c o  m*/
    FileNameExtensionFilter fileNameExtensionFilter = (FileNameExtensionFilter) fileExtFilter;
    String ext = fileNameExtensionFilter.getExtensions()[0];
    if (!ext.equalsIgnoreCase(FilenameUtils.getExtension(filePathName))) {
        filePathName += "." + ext;
    }
    return filePathName;
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Show dialog for exporting JFreechart object.
 *//*from  w  ww. j a va  2  s .  co m*/
public void openExportDialog(JFreeChart jfreechart) {

    JFileChooser chooser = new JFileChooser();
    String path0;
    File file;

    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Files", "jpg"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Files", "png"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("EPS Files", "eps"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG Files", "svg"));

    chooser.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));

    int returnVal = chooser.showSaveDialog(null);
    String fd = chooser.getFileFilter().getDescription();

    // Get selected FileFilter 
    String filter_extension = null;
    if (fd.equals("PNG Files")) {
        filter_extension = "png";
    }
    if (fd.equals("SVG Files")) {
        filter_extension = "svg";
    }
    if (fd.equals("JPEG Files")) {
        filter_extension = "jpg";
    }
    if (fd.equals("PDF Files")) {
        filter_extension = "pdf";
    }
    if (fd.equals("EPS Files")) {
        filter_extension = "eps";
    }

    // Cancel
    if (returnVal == JFileChooser.CANCEL_OPTION) {
        return;
    }

    // OK
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        path0 = chooser.getSelectedFile().getAbsolutePath();
        //System.out.println(path0);
        try {
            file = new File(path0);
            // Get extension (if any)
            String ext = JFUtils.getExtension(file);
            // No extension -> use selected Filter
            if (ext == null) {
                file = new File(path0 + "." + filter_extension);
                ext = filter_extension;
            }

            // File exists - overwrite ?
            if (file.exists()) {
                Object[] options = { "OK", "CANCEL" };
                int answer = JOptionPane.showOptionDialog(null, "File exists - Overwrite ?", "Warning",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                //System.out.println(answer+"");
            }

            // Export file
            export(file, jfreechart);
        } catch (Exception f) {
            // I/O - Error
        }
    }
}

From source file:org.martus.client.swingui.FxInSwingMainWindow.java

protected File showFileSaveDialog(String title, File directory, Vector<FormatFilter> filters) {
    while (true) {
        JFileChooser fileChooser = createFileChooser(title, directory, filters);

        int userResult = fileChooser.showSaveDialog(getCurrentActiveFrame().getSwingFrame());
        if (userResult != JFileChooser.APPROVE_OPTION)
            return null;

        File selectedFile = fileChooser.getSelectedFile();

        FormatFilter selectedFilter = (FormatFilter) fileChooser.getFileFilter();
        selectedFile = getFileWithExtension(selectedFile, selectedFilter.getExtension());

        if (!selectedFile.exists())
            return selectedFile;

        if (confirmDlg(getCurrentActiveFrame().getSwingFrame(), "OverWriteExistingFile"))
            return selectedFile;

        directory = selectedFile.getParentFile();
    }/*from   w w  w.  ja  v a 2  s  .c o  m*/
}

From source file:com.opendoorlogistics.core.utils.ui.FileBrowserPanel.java

private static JButton createBrowseButton(final boolean directoriesOnly, final String browserApproveButtonText,
        final JTextField textField, final FileFilter... fileFilters) {
    JButton browseButton = new JButton("...");
    browseButton.addActionListener(new ActionListener() {

        @Override/*  w  ww .  ja va  2  s  .c  o  m*/
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            if (textField.getText() != null) {
                File file = new File(textField.getText());

                // if the file doesn't exist but the directory does, get that
                if (!file.exists() && file.getParentFile() != null && file.getParentFile().exists()) {
                    file = file.getParentFile();
                }

                if (!directoriesOnly && file.isFile()) {
                    chooser.setSelectedFile(file);
                }

                if (file.isDirectory() && file.exists()) {
                    chooser.setCurrentDirectory(file);
                }
            }

            if (directoriesOnly) {
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            // add filters and automatically select correct one
            if (fileFilters.length == 1) {
                chooser.setFileFilter(fileFilters[0]);
            } else {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                    if (filter instanceof FileNameExtensionFilter) {
                        if (matchesFilter((FileNameExtensionFilter) filter, textField.getText())) {
                            chooser.setFileFilter(filter);
                        }
                    }
                }
            }

            if (chooser.showDialog(textField, browserApproveButtonText) == JFileChooser.APPROVE_OPTION) {
                //File selected = processSelectedFile(chooser.getSelectedFile());
                File selected = chooser.getSelectedFile();

                String path = selected.getPath();
                FileFilter filter = chooser.getFileFilter();
                if (filter != null && filter instanceof FileNameExtensionFilter) {

                    boolean found = matchesFilter(((FileNameExtensionFilter) chooser.getFileFilter()), path);

                    if (!found) {
                        String[] exts = ((FileNameExtensionFilter) chooser.getFileFilter()).getExtensions();
                        if (exts.length > 0) {
                            path = FilenameUtils.removeExtension(path);
                            path += "." + exts[0];
                        }
                    }

                }
                textField.setText(path);
            }
        }
    });

    return browseButton;
}

From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cancelButton) {
        this.setVisible(false);
        this.dispose();
    } else if (e.getSource() == saveChartButton) {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog/*from   w  w  w.  jav  a2s . c o  m*/
                .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)"));
        saveFileDialog.addChoosableFileFilter(
                new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)"));
        saveFileDialog
                .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)"));
        int save = saveFileDialog.showSaveDialog(this);
        if (save == JFileChooser.APPROVE_OPTION) {
            File file = saveFileDialog.getSelectedFile();
            int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue();
            int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue();

            ExtensionFileFilter filter = null;
            try {
                filter = (ExtensionFileFilter) saveFileDialog.getFileFilter();
                if (!filter.hasExtension(file)) {
                    file = filter.appendExtension(file);
                }
            } catch (ClassCastException ex) {
                // Try to infer the type of file by its extension
                FileFilter[] filters = saveFileDialog.getChoosableFileFilters();
                for (int i = 0; i < filters.length; ++i) {
                    if (filters[i] instanceof ExtensionFileFilter) {
                        filter = (ExtensionFileFilter) filters[i];
                        if (filter.hasExtension(file)) {
                            break;
                        }
                        filter = null;
                    }
                }

                if (filter == null) {
                    // Could not infer the type
                    JOptionPane.showMessageDialog(null,
                            "File type not specified!\nWhen giving file name, please also select one of the supported file types.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            // Save the chart to the specified file name
            try {
                String ext = filter.getExtension();
                if (ext.equals("jpeg")) {
                    ChartUtilities.saveChartAsJPEG(file, chart, width, height);
                } else if (ext.equals("png")) {
                    ChartUtilities.saveChartAsPNG(file, chart, width, height);
                } else {
                    VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height));
                    graphics.startExport();
                    chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height));
                    graphics.endExport();
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            this.setVisible(false);
            this.dispose();
        } else if (save == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:analysers.ExportValidated.java

@Override
public void analyze(Cell currentCell) {
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new FileNameExtensionFilter("Comma Separated Values", "csv"));
    fc.addChoosableFileFilter(new FileNameExtensionFilter("JSON file", "json"));
    int rv = fc.showSaveDialog(null);
    if (rv == JFileChooser.APPROVE_OPTION) {
        int b = Prefs.getInt(".TrackApp.FilterValidatedDialog.exportMean", 1);
        if (b != 0) {
            IJ.log("Exporting mean intensity values.");
        } else {//from   w  w w.j a  v a  2s .  co  m
            IJ.log("Exporting sum of intensity values.");
        }

        File ff = fc.getSelectedFile();
        String fn = fc.getSelectedFile().getAbsolutePath();

        if (fc.getFileFilter().getDescription().contains("JSON")) {
            if (!fn.toLowerCase().endsWith(".json")) {
                fn = fn + ".json";
                ff = new File(ff + ".json");
            }
            IJ.log("Writing a JSON file.");
        } else {
            if (!fn.toLowerCase().endsWith(".csv")) {
                fn = fn + ".csv";
                ff = new File(ff + ".csv");
            }
            IJ.log("Writing a CSV file.");
        }
        IJ.log("Writing to " + fn);

        if (fn.endsWith(".csv")) {
            writeCSV(ff);
        } else if (fn.endsWith(".json")) {
            writeJSON(ff);
        } else {
            IJ.log("Unknown output format for file name " + fn);
        }

    }
}

From source file:net.sf.jasperreports.swing.JRViewerToolbar.java

void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    // Add your handling code here:

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setLocale(this.getLocale());
    fileChooser.updateUI();//  w  w w .  j a  v a 2s . co m
    for (int i = 0; i < saveContributors.size(); i++) {
        fileChooser.addChoosableFileFilter(saveContributors.get(i));
    }

    if (saveContributors.contains(lastSaveContributor)) {
        fileChooser.setFileFilter(lastSaveContributor);
    } else if (saveContributors.size() > 0) {
        fileChooser.setFileFilter(saveContributors.get(0));
    }

    if (lastFolder != null) {
        fileChooser.setCurrentDirectory(lastFolder);
    }

    int retValue = fileChooser.showSaveDialog(this);
    if (retValue == JFileChooser.APPROVE_OPTION) {
        FileFilter fileFilter = fileChooser.getFileFilter();
        File file = fileChooser.getSelectedFile();

        lastFolder = file.getParentFile();

        JRSaveContributor contributor = null;

        if (fileFilter instanceof JRSaveContributor) {
            contributor = (JRSaveContributor) fileFilter;
        } else {
            int i = 0;
            while (contributor == null && i < saveContributors.size()) {
                contributor = saveContributors.get(i++);
                if (!contributor.accept(file)) {
                    contributor = null;
                }
            }

            if (contributor == null) {
                contributor = new JRPrintSaveContributor(viewerContext.getJasperReportsContext(), getLocale(),
                        viewerContext.getResourceBundle());
            }
        }

        lastSaveContributor = contributor;

        try {
            contributor.save(viewerContext.getJasperPrint(), file);
        } catch (JRException e) {
            if (log.isErrorEnabled()) {
                log.error("Save error.", e);
            }
            JOptionPane.showMessageDialog(this, viewerContext.getBundleString("error.saving"));
        }
    }
}