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:io.gameover.utilities.pixeleditor.Pixelizer.java

private void saveImage(String description, String extension, Encoder encoder) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileNameExtensionFilter(description, extension));
    if (fileChooser.showDialog(this, "Save") == JFileChooser.APPROVE_OPTION) {
        File f = fileChooser.getSelectedFile();
        try {//from  w ww  . java  2 s .  c  o  m
            encoder.saveImage(f, frames);
            JOptionPane.showMessageDialog(this, "File " + f.getName() + " saved!");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Failed to save " + f.getName() + ": " + e.getMessage(),
                    "Error occured", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
}

From source file:uk.ac.lkl.cram.ui.ModuleFrame.java

private void exportReport() {
    JFileChooser jfc = new JFileChooser();
    jfc.setAcceptAllFileFilterUsed(false);
    jfc.setDialogTitle("Export CRAM Module");
    FileFilter filter = new FileNameExtensionFilter("Word Document", "docx");
    jfc.setFileFilter(filter);
    jfc.setSelectedFile(new File(module.getModuleName() + ".docx"));
    //Open the dialog and wait for the user to provide a name for the file
    int returnVal = jfc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = jfc.getSelectedFile();
        //Add the file extension
        if (!jfc.getSelectedFile().getAbsolutePath().endsWith(".docx")) {
            file = new File(jfc.getSelectedFile() + ".docx");
        }/*from   ww w .  j a  va  2  s.c  o  m*/
        try {
            this.setCursor(WAIT);
            Report report = new Report(module);
            report.save(file);
        } catch (Docx4JException ex) {
            LOGGER.log(Level.SEVERE, "Failed to export report", ex);
            JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(), "Failed to export report",
                    JOptionPane.ERROR_MESSAGE);
        } finally {
            this.setCursor(Cursor.getDefaultCursor());
        }
    }
}

From source file:jboost.visualization.HistogramFrame.java

private File selectPDFFile() {

    File fFile = new File("default.pdf");
    JFileChooser fc = new JFileChooser();

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(new FileFilter() {

        public boolean accept(File f) {
            String path = f.getAbsolutePath();
            if (f.isDirectory() || path.endsWith(".pdf"))
                return true;
            else/*w w w .j  ava  2s . c  o  m*/
                return false;
        }

        public String getDescription() {
            return "PDF Files";
        }
    });

    // Set to a default name for save.
    fc.setSelectedFile(fFile);

    // Open chooser dialog
    int result = fc.showSaveDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
        return null;
    } else if (result == JFileChooser.APPROVE_OPTION) {
        fFile = fc.getSelectedFile();
        if (fFile.exists()) {
            int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?", "Confirm Overwrite",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.CANCEL_OPTION)
                return null;
        }
        return fFile;
    } else {
        return null;
    }
}

From source file:jboost.visualization.HistogramFrame.java

private File selectDumpFile() {

    File fFile = new File("ExamplesDumpFile.txt");
    JFileChooser fc = new JFileChooser();

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(new FileFilter() {

        public boolean accept(File f) {
            String path = f.getAbsolutePath();
            if (f.isDirectory() || path.endsWith(".txt"))
                return true;
            else//from  w w w .j  a  v a 2  s . co  m
                return false;
        }

        public String getDescription() {
            return "Text Files";
        }
    });

    // Set to a default name for save.
    fc.setSelectedFile(fFile);

    // Open chooser dialog
    int result = fc.showSaveDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
        return null;
    } else if (result == JFileChooser.APPROVE_OPTION) {
        fFile = fc.getSelectedFile();
        if (fFile.exists()) {
            int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?", "Confirm Overwrite",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.CANCEL_OPTION)
                return null;
        }
        return fFile;
    } else {
        return null;
    }
}

From source file:au.com.jwatmuff.eventmanager.gui.main.LoadCompetitionWindow.java

private void loadBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadBackupButtonActionPerformed
    File databaseStore = new File(Main.getWorkingDirectory(), "comps");
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("Event Manager Files", "evm"));

    JPanel optionsPanel = new JPanel();

    optionsPanel.setBorder(/*from w  ww . j av  a2s  .  c o m*/
            new CompoundBorder(new EmptyBorder(0, 10, 0, 10), new TitledBorder("Load backup options")));
    JCheckBox preserveIDCheckbox = new JCheckBox("Preserve competition ID");
    optionsPanel.add(preserveIDCheckbox);

    chooser.setAccessory(optionsPanel);

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        /* input zip file */
        File file = chooser.getSelectedFile();
        /* construct output directory */
        File dir = new File(databaseStore, file.getName());
        int suffix = 0;
        while (dir.exists()) {
            suffix++;
            dir = new File(databaseStore, file.getName() + "_" + suffix);
        }
        /* unzip */
        try {
            ZipUtils.unzipFile(dir, file);

            /* change id */
            Properties props = new Properties();
            FileReader fr = new FileReader(new File(dir, "info.dat"));
            props.load(fr);
            fr.close();
            if (!preserveIDCheckbox.isSelected()) {
                props.setProperty("UUID", UUID.randomUUID().toString());
            }
            props.setProperty("name", props.getProperty("name") + " - " + dateFormat.format(new Date()));
            FileWriter fw = new FileWriter(new File(dir, "info.dat"));
            props.store(fw, "");
            fw.close();

            /* update gui */
            checkDatabasesExecutor.schedule(checkDatabasesTask, 0, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            GUIUtils.displayError(null, "Error while opening file: " + e.getMessage());
        }
    }
}

From source file:org.pgptool.gui.ui.encryptone.EncryptOnePm.java

public ExistingFileChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new ExistingFileChooserDialog(findRegisteredWindowIfAny(), appProps,
                SOURCE_FOLDER) {//  ww w  . j a va 2 s  .c om
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);
                ofd.setDialogTitle(Messages.get("phrase.selectFileToEncrypt"));

                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(notEncryptedFiles);
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);
            }

            private FileFilter notEncryptedFiles = new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return !DecryptOnePm.isItLooksLikeYourSourceFile(f.getAbsolutePath());
                }

                @Override
                public String getDescription() {
                    return text("phrase.allExceptEncrypted");
                }
            };
        };
    }
    return sourceFileChooser;
}

From source file:GroupProject.OriginalChartUI.java

private void localBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_localBrowseButtonActionPerformed
    // TODO add your handling code here:
    JFileChooser fileChooser = new JFileChooser();
    FileTypeFilter fileFileter = new FileTypeFilter();
    fileChooser.setFileFilter(fileFileter);
    int returnVal = fileChooser.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fileChooser.getSelectedFile();
        //  FileName.setText(file.getName());
        //FileUpload.Upload(file);
        localDataResourceAddr.setText(file.getName());
    } else {/*from  w w w .  j  a v a 2s  . c o  m*/
        JOptionPane.showMessageDialog(null, "File access cancelled by user.", "Alert",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.opendoorlogistics.studio.appframe.AppFrame.java

@Override
public void importFile(final ImportFileType option) {

    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(option.getFilter());

    IOUtils.setFile(PreferencesManager.getSingleton().getLastImportFile(option), chooser);
    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;//from   w  w w. j  av  a  2s. co m
    }

    final File file = chooser.getSelectedFile();
    PreferencesManager.getSingleton().setLastImportFile(file, option);

    importFile(file, option);

}

From source file:com.opendoorlogistics.studio.appframe.AppFrame.java

@Override
public void openDatastoreWithUserPrompt() {
    if (!canCloseDatastore()) {
        return;/*from  w  ww  .j  a  va 2 s . c om*/

    }
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(ImportFileType.EXCEL.getFilter());

    File defaultDir = PreferencesManager.getSingleton().getFile(PrefKey.LAST_IO_DIR);
    if (defaultDir != null) {
        IOUtils.setFile(defaultDir, chooser);
    }

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        final File file = chooser.getSelectedFile();

        openFile(file);
    }
    updateAppearance();
}

From source file:dylemator.UserResultList.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (this.filenameCombo.getSelectedIndex() == 0)
        return;/*  w  w w  .  j  a v a 2 s.  c o  m*/
    String sheetName = (String) this.filenameCombo.getSelectedItem();
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(sheetName);
    Row headerRow = sheet.createRow(0);
    String[] headers = exportData.get(0);
    int numOfColumns = headers.length;
    for (int i = 0, j = 0; i < numOfColumns; i++) {
        if (i == 1 || i == 2 || i == 3) // opuszcz. date, imie, nazwisko
            continue;
        Cell cell = headerRow.createCell(j++);
        cell.setCellValue(headers[i]);
    }

    int rowCount = exportData.size();
    for (int rownum = 1; rownum < rowCount; rownum++) {
        Row row = sheet.createRow(rownum);
        String[] values = exportData.get(rownum);
        for (int i = 0, j = 0; i < numOfColumns; i++) {
            if (i == 1 || i == 2 || i == 3) // opuszcz. date, imie, nazwisko
                continue;
            Cell cell = row.createCell(j++);
            cell.setCellValue(values[i]);
        }
    }

    String defaultFilename = "Export.xlsx";
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    f.setSelectedFile(new File(defaultFilename));
    f.setDialogTitle("Wybierz nazw dla pliku eksportu");
    f.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter ff = new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().endsWith(".xlsx"))
                return true;
            return false;
        }

        @Override
        public String getDescription() {
            return "";
        }
    };
    f.setFileFilter(ff);

    File file = null;
    int save = f.showSaveDialog(this);
    if (save == JFileChooser.APPROVE_OPTION)
        file = f.getSelectedFile();
    else
        return;

    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserResultList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UserResultList.class.getName()).log(Level.SEVERE, null, ex);
    }
}