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.nekorp.workflow.desktop.view.ServicioView.java

private void ordenServicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ordenServicioActionPerformed
    try {/*w  w w  .j a v  a  2 s  . c om*/
        if (servicioMetaData.isEditado()) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.aplication.guardaServicio();
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
        ParametrosReporteOS param = new ParametrosReporteOS();
        Object[] options = { "Evaluacin", "Presupuesto" };
        int n = javax.swing.JOptionPane.showOptionDialog(mainFrame, "Qu tipo de reporte desea generar?",
                "Tipo de reporte", javax.swing.JOptionPane.YES_NO_OPTION,
                javax.swing.JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
        if (n == javax.swing.JOptionPane.CLOSED_OPTION) {
            return;
        }
        param.setConCosto(!(n == javax.swing.JOptionPane.YES_OPTION));
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo PDF", "pdf");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        String prefijo;
        if (param.isConCosto()) {
            prefijo = "/Orden-Servicio-presupuesto-";
        } else {
            prefijo = "/Orden-Servicio-evaluacion-";
        }
        File f = new File(
                new File(homePath + prefijo + this.viewServicioModel.getId() + ".pdf").getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showSaveDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            param.setDestination(chooser.getSelectedFile());
            this.aplication.generaOrdenServicio(param);
        }
    } catch (IllegalArgumentException e) {
        //no lo guardo por que tenia horribles errores... tambien especializar la excepcion
    } catch (IOException ex) {
        ServicioView.LOGGER.error("error al exportar orden de servicio", ex);
    } finally {
        this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    }
}

From source file:dotaSoundEditor.Controls.ItemPanel.java

@Override
protected File promptUserForNewFile(String wavePath) {
    DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
    String waveString = selectedTreeNode.getUserObject().toString();
    String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", "");

    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav")
            : new FileNameExtensionFilter("MP3s", "mp3");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());

        int startIndex = -1;
        int endIndex = -1;
        //Get the actual value for the wavestring key-value pair.
        if (waveString.contains("\"wave\"")) {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3);
        } else //Some wavestrings don't have the "wave" at the beginning for some reason
        {//  w  w  w .  j  a v  a 2  s  .c om
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1);
        }
        String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
        String waveStringNormalizedFilePath = waveStringFilePath.substring(0,
                waveStringFilePath.lastIndexOf("\""));
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", "");
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", "");

        Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            if (waveString.contains("//")) {
                waveString = waveString
                        .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), "");
            }
            waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath
                    + "\" //Replaced by: " + chosenFile.getFileName().toString());
            selectedTreeNode.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.ga.forms.DailyLogUI.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    System.out.print(/* w w w .  j  a  v  a  2  s.  c  o  m*/
            "REGEX: " + monthCombo.getSelectedItem().toString() + "-" + yearCombo.getSelectedItem().toString());
    JFrame fileChooserFrame = new JFrame();
    JFileChooser saveFileDialog = new JFileChooser();
    FileNameExtensionFilter fileExtentionFilter = new FileNameExtensionFilter("Comma Seperated Values (*.csv)",
            "csv");
    saveFileDialog.setFileFilter(fileExtentionFilter);
    int saveFileDialogStatus = saveFileDialog.showSaveDialog(fileChooserFrame);
    if (saveFileDialogStatus == JFileChooser.APPROVE_OPTION) {
        String fileSaveDetails = saveFileDialog.getSelectedFile().toString();
        args = new HashMap();
        HashMap regex = new HashMap();
        regex.put("$regex",
                monthCombo.getSelectedItem().toString() + "-" + yearCombo.getSelectedItem().toString());
        args.put("date", regex);
        DailyLogRecord record = new DailyLogRecord();
        ArrayList logs = record.retrieveRecord(args);
        String[] columnNames = new String[] { "Date", "Day", "In", "Out", "Break", "Duration", "Under-Time",
                "Over-Time" };
        ArrayList data = null;
        if (!logs.isEmpty()) {
            data = new ArrayList();
            data.add(String.join(",", columnNames));
            for (int logIndex = 0; logIndex < logs.size(); logIndex++) {
                JSONObject logJSONOBject = new JSONObject((Map) logs.get(logIndex));
                String csvRecord = logJSONOBject.get("date").toString() + ","
                        + logJSONOBject.get("day").toString() + "," + logJSONOBject.get("check-in").toString()
                        + "," + logJSONOBject.get("check-out").toString() + ","
                        + logJSONOBject.get("break").toString() + "," + logJSONOBject.get("duration").toString()
                        + "," + logJSONOBject.get("under-time").toString() + ","
                        + logJSONOBject.get("over-time").toString();
                data.add(csvRecord);
            }

        }
        DailyLogCSVExport csvExporter = new DailyLogCSVExport();
        csvExporter.save(data, fileSaveDetails);
    }
}

From source file:org.pgptool.gui.ui.importkey.KeyImporterPm.java

public MultipleFilesChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new MultipleFilesChooserDialog(findRegisteredWindowIfAny(), appProps,
                BROWSE_FOLDER) {/* w w  w. j  a v a 2 s  .com*/
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);
                ofd.setDialogTitle(Messages.get("action.importKey"));

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

            private FileFilter keyFilesFilter = new FileFilter() {
                @Override
                public boolean accept(File f) {
                    if (f.isDirectory() || !f.isFile()) {
                        return true;
                    }
                    if (!isExtension(f.getName(), EXTENSIONS)) {
                        return false;
                    }

                    // NOTE: Although it gives best results -- I have a
                    // slight concern that this might be too heavy operation
                    // to perform thorough -- check for each file
                    // contents. My hope is that since we're checking only
                    // key files it shouldn't be a problem. Non-key files
                    // with same xtensions will not take a long time to fail
                    try {
                        Key readKey = keyFilesOperations.readKeyFromFile(f.getAbsolutePath());
                        Preconditions.checkState(readKey != null, "Key wasn't parsed");

                        Key existingKey = keyRingService.findKeyById(readKey.getKeyInfo().getKeyId());
                        if (existingKey == null) {
                            return true;
                        }
                        if (!existingKey.getKeyData().isCanBeUsedForDecryption()
                                && readKey.getKeyData().isCanBeUsedForDecryption()) {
                            return true;
                        }
                        return false;
                    } catch (Throwable t) {
                        // in this case it's not an issue. So it's debug
                        // level
                        log.debug(
                                "File is not accepte for file chooser becasue was not able to read it as a key",
                                t);
                    }

                    return false;
                }

                private boolean isExtension(String fileName, String[] extensions) {
                    String extension = FilenameUtils.getExtension(fileName);
                    if (!StringUtils.hasText(extension)) {
                        return false;
                    }

                    for (String ext : extensions) {
                        if (ext.equalsIgnoreCase(extension)) {
                            return true;
                        }
                    }
                    return false;
                }

                @Override
                public String getDescription() {
                    return "Key files (.asc, .bpg)";
                }
            };
        };
    }
    return sourceFileChooser;
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }
        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileNameSignature = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);//from   w  w w .  j a va2  s.  co  m

        txtPathSig.setText(fileNameSignature);

        try {

            File images = new File(fileNameSignature);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:com.smanempat.controller.ControllerClassification.java

public void chooseFile(ActionEvent evt, JTextField txtFileDirectory, JTextField txtNumberOfK,
        JLabel labelJumlahData, JButton buttonProses, JTable tablePreview) {
    try {//from ww w.  j  a  va 2  s.c  o m
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Excel File", "xls",
                "xlsx");
        fileChooser.setFileFilter(fileNameExtensionFilter);

        if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
            txtFileDirectory.setText(fileChooser.getSelectedFile().getAbsolutePath());
            System.out.println("Good, File Chooser runing well!");
            if (txtFileDirectory.getText().endsWith(".xls") || txtFileDirectory.getText().endsWith(".xlsx")) {
                showOnTable(evt, txtFileDirectory, tablePreview);
                labelJumlahData.setText(tablePreview.getRowCount() + " Data");
                txtNumberOfK.setEnabled(true);
                txtNumberOfK.requestFocus();
                buttonProses.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null,
                        "File dataset harus file spreadsheet dengan ekstensi *xls atau *.xlsx!", "Error",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon("src/com/smanempat/image/fail.png"));
                txtFileDirectory.setText("");
                chooseFile(evt, txtFileDirectory, txtNumberOfK, labelJumlahData, buttonProses, tablePreview);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.ox.cbrg.cpfp.uploadapp.UploadApplet.java

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed

    // Create & show file chooser with extension filter as per applet param
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new CustomFileFilter(fileExtensions));
    fc.setMultiSelectionEnabled(true);//  w w w.  ja v  a  2s  .  co  m
    fc.showOpenDialog(UploadApplet.this);

    // Add selected files to upload queue
    File[] selFiles = fc.getSelectedFiles();
    addFiles(selFiles);

}

From source file:firmadigital.Firma.java

private void cmdExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdExaminarActionPerformed
    JFileChooser fileChooser = new JFileChooser();

    txtUbicacion.setText("");
    lblNombreArchivo.setText("");
    lblRutaArchivo.setText("");

    String signFileName = txtUbicacion.getText();
    File directory = new File(signFileName).getParentFile();
    fileChooser.setCurrentDirectory(directory);
    FileNameExtensionFilter filter;
    filter = new FileNameExtensionFilter("XML file", "xml");
    fileChooser.setFileFilter(filter);
    fileChooser.setFileHidingEnabled(true);
    /*Remove All File option*/
    fileChooser.setAcceptAllFileFilterUsed(false);

    if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        String selectedFile = fileChooser.getSelectedFile().getAbsolutePath();
        txtUbicacion.setText(selectedFile);
        lblNombreArchivo.setText(fileChooser.getSelectedFile().getName());
        lblRutaArchivo.setText(fileChooser.getSelectedFile().getParent());
    }/*from   ww  w  .ja  v a  2 s.  co  m*/
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Ask the user for a certain file path// w  w w. j a va2  s  .co  m
 * 
 * @param chooser the {@link JFileChooser} to use
 * @param filter the file filter
 * @param title the title of the dialog
 * 
 * @return the selected file or null
 */
private String askForPath(JFileChooser chooser, FileFilter filter, String title) {
    chooser.setDialogTitle(title);
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile().getAbsolutePath();
    }

    return null;
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnAddFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAddFileActionPerformed
{//GEN-HEADEREND:event_btnAddFileActionPerformed

    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx", "xlsm", "xlt", "xlsb",
            "xltx", "xltm", "xls", "xlt", "xls");

    chooser.setFileFilter(filter);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);

    int res = chooser.showOpenDialog(null);

    if (res == JFileChooser.APPROVE_OPTION) {

        File file = chooser.getSelectedFile();

        // checking file extension. it must be excel file. 
        if (file.equals(filter)) {
            JOptionPane.showMessageDialog(null, "Wrong File selected", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }//from w w w. j a v  a2s  .c o  m

        fileName = file.getAbsolutePath();
        txtPath.setText(fileName);

    }

}