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:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java

@Override
public Collection<Throwable> call() throws Exception {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    List<BamFileRef> bams = new ArrayList<BamFileRef>();

    final List<String> args = getInputFiles();
    List<File> IN = new ArrayList<File>();

    if (args.isEmpty()) {
        LOG.info("NO BAM provided; Opening dialog");
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileFilter() {
            @Override/*from  ww  w  . j a  va 2 s  . co  m*/
            public String getDescription() {
                return "Indexed BAM files.";
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                return acceptBam(f);
            };
        });
        chooser.setMultiSelectionEnabled(true);
        if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
            return wrapException("user pressed cancel");
        }
        File fs[] = chooser.getSelectedFiles();
        if (fs != null)
            IN.addAll(Arrays.asList(chooser.getSelectedFiles()));
    } else {
        for (String arg : args) {
            File filename = new File(arg);
            if (!acceptBam(filename)) {
                return wrapException(
                        "Cannot use " + filename + " as input Bam. bad extenstion ? index missing ?");
            }
            IN.add(filename);
        }
    }

    for (File in : IN) {
        try {
            bams.add(create(in));
        } catch (Exception err) {
            return wrapException(err);
        }
    }
    if (bams.isEmpty()) {
        return wrapException("No Bam file");
    }
    LOG.info("showing BAM frame");
    final BamFrame frame = new BamFrame(bams);
    frame.igvIP = super.IGV_HOST;
    frame.igvPort = super.IGV_PORT;
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                frame.setBounds(50, 50, screen.width - 100, screen.height - 100);
                frame.setVisible(true);
            }
        });
    } catch (Exception err) {
        err.printStackTrace();
        System.exit(-1);
    }

    return RETURN_OK;
}

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();//from   w w  w . ja  va 2 s. c o 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"));
        }
    }
}

From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java

/**
 *
 *
 * @param saveAs//from   w ww  . jav a  2 s  .c om
 * @param file
 * @param profile
 *
 * @return
 */
public File saveConnection(boolean saveAs, File file, SshToolsConnectionProfile profile) {
    if (profile != null) {
        if ((file == null) || saveAs) {
            String prefsDir = super.getApplication().getApplicationPreferencesDirectory().getAbsolutePath();
            JFileChooser fileDialog = new JFileChooser(prefsDir);

            fileDialog.setFileFilter(connectionFileFilter);

            int ret = fileDialog.showSaveDialog(this);

            if (ret == fileDialog.CANCEL_OPTION) {
                return null;
            }

            file = fileDialog.getSelectedFile();

            if (!file.getName().toLowerCase().endsWith(".xml")) {
                file = new File(file.getAbsolutePath() + ".xml");
            }
        }

        try {
            if (saveAs && file.exists()) {
                if (JOptionPane.showConfirmDialog(this, "File already exists. Are you sure?", "File exists",
                        JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
                    return null;
                }
            }

            // Check to make sure its valid
            if (file != null) {
                // Save the connection details to file
                log.debug("Saving connection to " + file.getAbsolutePath());
                profile.save(file.getAbsolutePath());

                if (profile == getCurrentConnectionProfile()) {
                    log.debug("Current connection saved, disabling save action.");
                    setNeedSave(false);
                }

                return file;
            } else {
                showExceptionMessage("The file specified is invalid!", "Save Connection");
            }
        } catch (InvalidProfileFileException e) {
            showExceptionMessage(e.getMessage(), "Save Connection");
        }
    }

    return null;
}

From source file:org.samjoey.gui.GraphicalViewer.java

private void jButton_Parser_OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Parser_OpenActionPerformed
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    String[] exts = new String[2];
    exts[0] = "pgn";
    exts[1] = "jsca";
    FileNameExtensionFilter filter = new FileNameExtensionFilter(".pgn or .jsca files ONLY!", exts);
    fc.setFileFilter(filter);
    int returnVal = fc.showDialog(this, "Parse");

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final java.io.File file = fc.getSelectedFile();
        //This is where a real application would open the file.
        this.jTextField_Parser.setText(file.getName());
        (new Thread() {
            @Override/* ww w.j  av  a2  s. co m*/
            public void run() {
                selectedPGN(file);
            }
        }).start();
    } else {
    }
}

From source file:com.igormaznitsa.sciareto.ui.MainFrame.java

@Nullable
@Override//ww w  .jav  a  2  s. co  m
public File createMindMapFile(@Nullable final File folder) {
    final JFileChooser chooser = new JFileChooser(folder);
    chooser.setDialogTitle("Create new Mind Map");
    chooser.setFileFilter(MMDEditor.MMD_FILE_FILTER);
    chooser.setMultiSelectionEnabled(false);
    chooser.setApproveButtonText("Create");

    File result = null;

    if (chooser.showSaveDialog(Main.getApplicationFrame()) == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        if (!file.getName().endsWith(".mmd")) {
            file = new File(file.getAbsolutePath() + ".mmd");
        }

        if (file.exists()) {
            DialogProviderManager.getInstance().getDialogProvider()
                    .msgError("File '" + file + "' already exists!");
        } else {
            try {
                final MindMap mindMap = new MindMap(null, true);
                final String text = mindMap.write(new StringWriter()).toString();
                SystemUtils.saveUTFText(file, text);
                result = file;
            } catch (IOException ex) {
                DialogProviderManager.getInstance().getDialogProvider()
                        .msgError("Can't save mind map into file '" + file.getName() + "'");
            }
        }
    }
    return result;
}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void ButtonRapportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonRapportActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    String pattern = null;//from www  .j  ava  2  s  . co  m
    String path;
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JASPER files", "jasper");
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(this);
    chooser.setMultiSelectionEnabled(false);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        pattern = chooser.getSelectedFile().getPath();
    }
    FileNameExtensionFilter filterpath = new FileNameExtensionFilter("PDF files", "pdf");
    JFileChooser chooserpath = new JFileChooser();
    chooserpath.setFileFilter(filterpath);
    int returnSave = chooserpath.showSaveDialog(this);
    if (returnSave == JFileChooser.APPROVE_OPTION) {
        path = chooserpath.getSelectedFile().getPath();

        if (!path.contains("pdf")) {
            path = path + ".pdf";
            String a = "\\";
        }
        pattern = pattern.replace("\\", "\\" + "\\");
        path = path.replace("\\", "\\" + "\\");

        ReportCreator creator = new ReportCreator();
        int a = creator.CreateReportDeal(pattern, idd, path);
        if (a == 1) {
            File file = new File(path.toString());
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException ex) {
                Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:org.pgptool.gui.ui.decryptone.DecryptOnePm.java

public ExistingFileChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new ExistingFileChooserDialog(findRegisteredWindowIfAny(), appProps,
                SOURCE_FOLDER) {/*w  w  w  .jav a2 s . c o m*/
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);

                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(
                        new FileNameExtensionFilter("Encrypted files (.gpg, .pgp, .asc)", EXTENSIONS));
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);

                ofd.setDialogTitle(text("phrase.selectFileToDecrypt"));
            }

            @Override
            protected String handleFileWasChosen(String filePathName) {
                if (filePathName == null) {
                    return null;
                }
                sourceFile.setValueByOwner(filePathName);
                return filePathName;
            }
        };
    }
    return sourceFileChooser;
}

From source file:ca.canucksoftware.clockthemebuilder.ThemeBuilderView.java

private File loadFileChooser(javax.swing.filechooser.FileFilter ff, String saveName) {
    File result;//from w  w  w  .  j a v  a  2 s . c  o m
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    fc.setMultiSelectionEnabled(false);
    if (ff != null) {
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(ff);
    } else {
        fc.setAcceptAllFileFilterUsed(true);
    }
    if (saveName == null) {
        fc.setDialogTitle("");
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    } else {
        fc.setDialogTitle("Save As...");
        fc.setSelectedFile(new File(saveName));
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    }
    return result;
}

From source file:org.jfree.chart.demo.SuperDemo.java

private void exportToPDF() {
    java.awt.Component component = chartContainer.getComponent(0);
    if (component instanceof ChartPanel) {
        JFileChooser jfilechooser = new JFileChooser();
        jfilechooser.setName("untitled.pdf");
        jfilechooser.setFileFilter(new FileFilter() {

            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".pdf");
            }/*  w  ww  .j  a v  a 2s .  c  o m*/

            public String getDescription() {
                return "Portable Document Format (PDF)";
            }

        });
        int i = jfilechooser.showSaveDialog(this);
        if (i == 0) {
            ChartPanel chartpanel = (ChartPanel) component;
            try {
                JFreeChart jfreechart = (JFreeChart) chartpanel.getChart().clone();
                PDFExportTask pdfexporttask = new PDFExportTask(jfreechart, chartpanel.getWidth(),
                        chartpanel.getHeight(), jfilechooser.getSelectedFile());
                Thread thread = new Thread(pdfexporttask);
                thread.start();
            } catch (CloneNotSupportedException clonenotsupportedexception) {
                clonenotsupportedexception.printStackTrace();
            }
        }
    } else {
        String s = "Unable to export the selected item.  There is ";
        s = s + "either no chart selected,\nor else the chart is not ";
        s = s + "at the expected location in the component hierarchy\n";
        s = s + "(future versions of the demo may include code to ";
        s = s + "handle these special cases).";
        JOptionPane.showMessageDialog(this, s, "PDF Export", 1);
    }
}

From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java

/**
 *
 *//*from  w  w  w.ja  v  a 2 s . c o  m*/
public void editConnection() {
    // Create a file chooser with the current directory set to the
    // application home
    JFileChooser fileDialog = new JFileChooser(PreferencesStore.get(PREF_CONNECTION_FILE_DIRECTORY,
            System.getProperty("sshtools.home", System.getProperty("user.home"))));
    fileDialog.setFileFilter(connectionFileFilter);

    // Show it
    int ret = fileDialog.showOpenDialog(this);

    // If we've approved the selection then process
    if (ret == fileDialog.APPROVE_OPTION) {
        PreferencesStore.put(PREF_CONNECTION_FILE_DIRECTORY,
                fileDialog.getCurrentDirectory().getAbsolutePath());

        // Get the file
        File f = fileDialog.getSelectedFile();

        // Load the profile
        SshToolsConnectionProfile p = new SshToolsConnectionProfile();

        try {
            p.open(f);

            if (editConnection(p)) {
                saveConnection(false, f, p);
            }
        } catch (IOException ioe) {
            showErrorMessage(this, "Failed to load connection profile.", "Error", ioe);
        }
    }
}