Example usage for javax.swing JFileChooser addChoosableFileFilter

List of usage examples for javax.swing JFileChooser addChoosableFileFilter

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "Adds a filter to the list of user choosable file filters.")
public void addChoosableFileFilter(FileFilter filter) 

Source Link

Document

Adds a filter to the list of user choosable file filters.

Usage

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

private void letUserSelectAnImage() {
    JFileChooser fc = new JFileChooser();
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new MyFilter());
    int returnVal = fc.showOpenDialog(this);

    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;/* w w  w  .  ja  v  a 2 s .co  m*/
    }

    File file = fc.getSelectedFile();
    if (fileNameEndWithImageExtension(file.getName())) {
        loadImage(file);
    }
}

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/*w  w w  . j  a  v a2 s.  c o m*/
        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 ww. java  2  s. 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  w  ww. j  a v a2  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:parser.esperanto.gui.FileInputPanel.java

private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Szvegfjl (*.txt)", "txt");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setCurrentDirectory(new File("./src/main/resources/text/"));

    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        String path = fileChooser.getSelectedFile().getAbsolutePath();
        try {/*ww w . java2  s  .c o  m*/
            readFile(path);
            setOutput();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "A fjl nem tallhat");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Beolvassi hiba");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
}

From source file:pcgen.gui2.dialog.ExportDialog.java

private void export(boolean pdf) {
    UIPropertyContext context = UIPropertyContext.createContext("ExportDialog");
    final JFileChooser fcExport = new JFileChooser();
    fcExport.setFileSelectionMode(JFileChooser.FILES_ONLY);
    File baseDir = null;//from   w  ww  .  jav a 2  s  . co m
    {
        String path;
        if (pdf) {
            path = context.getProperty(PDF_EXPORT_DIR_PROP);
        } else {
            path = context.getProperty(HTML_EXPORT_DIR_PROP);
        }
        if (path != null) {
            baseDir = new File(path);
        }
    }
    if (baseDir == null || !baseDir.isDirectory()) {
        baseDir = SystemUtils.getUserHome();
    }
    fcExport.setCurrentDirectory(baseDir);

    URI uri = fileList.getSelectedValue();
    String extension = ExportUtilities.getOutputExtension(uri.toString(), pdf);
    if (pdf) {
        FileFilter fileFilter = new FileNameExtensionFilter("PDF Documents (*.pdf)", "pdf");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else if ("htm".equalsIgnoreCase(extension) || "html".equalsIgnoreCase(extension)) {
        FileFilter fileFilter = new FileNameExtensionFilter("HTML Documents (*.htm, *.html)", "htm", "html");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else if ("xml".equalsIgnoreCase(extension)) {
        FileFilter fileFilter = new FileNameExtensionFilter("XML Documents (*.xml)", "xml");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else {
        String desc = extension + " Files (*." + extension + ")";
        fcExport.addChoosableFileFilter(new FileNameExtensionFilter(desc, extension));
    }
    String name;
    File path;
    if (!partyBox.isSelected()) {
        CharacterFacade character = (CharacterFacade) characterBox.getSelectedItem();
        path = character.getFileRef().get();
        if (path != null) {
            path = path.getParentFile();
        } else {
            path = new File(PCGenSettings.getPcgDir());
        }
        name = character.getTabNameRef().get();
        if (StringUtils.isEmpty(name)) {
            name = character.getNameRef().get();
        }
    } else {
        path = new File(PCGenSettings.getPcgDir());
        name = "Entire Party";
    }
    if (pdf) {
        fcExport.setSelectedFile(new File(path, name + ".pdf"));
    } else {
        fcExport.setSelectedFile(new File(path, name + "." + extension));
    }
    fcExport.setDialogTitle("Export " + name);
    if (fcExport.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;
    }

    final File outFile = fcExport.getSelectedFile();
    if (pdf) {
        context.setProperty(PDF_EXPORT_DIR_PROP, outFile.getParent());
    } else {
        context.setProperty(HTML_EXPORT_DIR_PROP, outFile.getParent());
    }

    if (StringUtils.isEmpty(outFile.getName())) {
        pcgenFrame.showErrorMessage("PCGen", "You must set a filename.");
        return;
    }

    if (outFile.isDirectory()) {
        pcgenFrame.showErrorMessage("PCGen", "You cannot overwrite a directory with a file.");
        return;
    }

    if (outFile.exists() && !SettingsHandler.getAlwaysOverwrite()) {
        int reallyClose = JOptionPane.showConfirmDialog(this,
                "The file " + outFile.getName() + " already exists, are you sure you want to overwrite it?",
                "Confirm overwriting " + outFile.getName(), JOptionPane.YES_NO_OPTION);

        if (reallyClose != JOptionPane.YES_OPTION) {
            return;
        }
    }
    if (pdf) {
        new PDFExporter(outFile, extension, name).execute();
    } else {
        if (!printToFile(outFile)) {
            String message = "The character export failed. Please see the log for details.";
            pcgenFrame.showErrorMessage(Constants.APPLICATION_NAME, message);
            return;
        }
        maybeOpenFile(outFile);
        Globals.executePostExportCommandStandard(outFile.getAbsolutePath());
    }
}

From source file:pcgen.gui2.prefs.LookAndFeelPanel.java

private void selectThemePack() {
    JFileChooser fc = new JFileChooser(ConfigurationSettings.getThemePackDir());
    fc.setDialogTitle(LanguageBundle.getString("in_Prefs_chooseSkinDialogTitle"));

    String theme = LookAndFeelManager.getCurrentThemePack();

    if (StringUtils.isNotEmpty(theme)) {
        fc.setCurrentDirectory(new File(LookAndFeelManager.getCurrentThemePack()));
        fc.setSelectedFile(new File(LookAndFeelManager.getCurrentThemePack()));
    }//w w w.j a v a 2s. c  o m

    fc.addChoosableFileFilter(new ThemePackFilter());

    if (fc.showOpenDialog(getParent().getParent()) == JFileChooser.APPROVE_OPTION) //ugly, but it works
    {
        File newTheme = fc.getSelectedFile();

        if (newTheme.isDirectory() || (!newTheme.getName().endsWith("themepack.zip"))) {
            ShowMessageDelegate.showMessageDialog(LanguageBundle.getString("in_Prefs_notAThemeErrorItem"),
                    Constants.APPLICATION_NAME, MessageType.ERROR);
        } else {
            LookAndFeelManager.setSelectedThemePack(newTheme.getAbsolutePath());
        }
    }
}

From source file:pl.otros.logview.gui.Log4jPatternParserEditor.java

protected void saveParser() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(AllPluginables.USER_LOG_IMPORTERS);
    chooser.addChoosableFileFilter(new FileFilter() {

        @Override/*w  ww .  jav  a 2  s . c o  m*/
        public String getDescription() {
            return "*.pattern files";
        }

        @Override
        public boolean accept(File f) {
            return f.getName().endsWith(".pattern") || f.isDirectory();
        }
    });
    int showSaveDialog = chooser.showSaveDialog(this);
    if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        if (!selectedFile.getName().endsWith(".pattern")) {
            selectedFile = new File(selectedFile.getAbsolutePath() + ".pattern");
        }
        if (selectedFile.exists() && JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this,
                "Do you want to overwrite file " + selectedFile.getName() + "?", "Save parser",
                JOptionPane.YES_NO_OPTION)) {
            return;
        }
        String text = propertyEditor.getText();
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(selectedFile);
            IOUtils.write(text, output);
            LogImporterUsingParser log4jImporter = createLog4jImporter(text);
            otrosApplication.getAllPluginables().getLogImportersContainer().addElement(log4jImporter);
        } catch (Exception e) {
            LOGGER.severe("Can't save parser: " + e.getMessage());
            JOptionPane.showMessageDialog(this, "Can't save parser: " + e.getMessage(), "Error saving parser",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:plugin.notes.gui.NotesView.java

/**
 *  {@literal handle File->Open.} Will open any .gmn files, and import them into your
 *  notes structure//from ww  w .  j a va  2s  .c  o m
 */
public void handleOpen() {
    // TODO fix
    String sFile = SettingsHandler.getGMGenOption(OPTION_NAME_LASTFILE, System.getProperty("user.dir"));
    File defaultFile = new File(sFile);
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(defaultFile);
    chooser.addChoosableFileFilter(getFileType());
    chooser.setFileFilter(getFileType());
    chooser.setMultiSelectionEnabled(true);
    Component component = GMGenSystem.inst;
    Cursor originalCursor = component.getCursor();
    component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    int option = chooser.showOpenDialog(GMGenSystem.inst);

    if (option == JFileChooser.APPROVE_OPTION) {
        for (File noteFile : chooser.getSelectedFiles()) {
            SettingsHandler.setGMGenOption(OPTION_NAME_LASTFILE, noteFile.toString());

            if (noteFile.toString().endsWith(EXTENSION)) {
                openGMN(noteFile);
            }
        }
    }

    GMGenSystem.inst.setCursor(originalCursor);
    refreshTree();
}

From source file:plugin.notes.gui.NotesView.java

/**
 *  Exports a node out to a gmn file.//from   ww  w .ja v a2 s .  c  om
 *
 *@param  node  node to export to file
 */
private void exportFile(NotesTreeNode node) {
    JFileChooser fLoad = new JFileChooser();
    String sFile = SettingsHandler.getGMGenOption(OPTION_NAME_LASTFILE, "");
    new File(sFile);

    FileFilter ff = getFileType();
    fLoad.addChoosableFileFilter(ff);
    fLoad.setFileFilter(ff);

    int returnVal = fLoad.showSaveDialog(this);

    try {
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String fileName = fLoad.getSelectedFile().getName();
            String dirName = fLoad.getSelectedFile().getParent();

            String extension = EXTENSION;
            if (fileName.indexOf(extension) < 0) {
                fileName += extension;
            }

            File expFile = new File(dirName + File.separator + fileName);

            if (expFile.exists()) {
                int choice = JOptionPane.showConfirmDialog(this, "File Exists, Overwrite?", "File Exists",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

                if (choice == JOptionPane.NO_OPTION) {
                    return;
                }
            }

            SettingsHandler.setGMGenOption(OPTION_NAME_LASTFILE, expFile.toString());
            writeNotesFile(expFile, node);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error Writing File");
        Logging.errorPrint("Error Writing to file: " + e.getMessage(), e);
    }
}