Example usage for javax.swing.filechooser FileNameExtensionFilter FileNameExtensionFilter

List of usage examples for javax.swing.filechooser FileNameExtensionFilter FileNameExtensionFilter

Introduction

In this page you can find the example usage for javax.swing.filechooser FileNameExtensionFilter FileNameExtensionFilter.

Prototype

public FileNameExtensionFilter(String description, String... extensions) 

Source Link

Document

Creates a FileNameExtensionFilter with the specified description and file name extensions.

Usage

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public SpinCADBank fileOpenBank() {
    loadRecentBankFileList();/*w  ww  .  j a  v a2  s  . c  om*/
    SpinCADBank b = null;
    File file = null;

    final String newline = "\n";
    // In response to a button click:
    FileNameExtensionFilter filter = new FileNameExtensionFilter("SpinCAD Bank Files", "spbk");
    fc.setFileFilter(filter);
    fc.setAccessory(recentBankFileList);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int returnVal = fc.showOpenDialog(new JFrame());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();
        // This is where a real application would open the file.
        System.out.println("Opening: " + file.getName() + "." + newline);
        try {
            // first, open bank, then open patch 0
            b = fileReadBank(file);
        } catch (Exception e) { // thrown over in SpinCADFile.java
            e.printStackTrace();
            //            MessageBox("File open failed!", "This spbk file may be from\nan incompatible version of \nSpinCAD Designer.");
        }
    } else {
        System.out.println("Open command cancelled by user." + newline);
    }
    String filePath = file.getPath();
    String fileName = file.getName();
    saveMRUBankFolder(filePath);
    recentBankFileList.add(file);
    // XXX debug looks like we kinda have the same info in 2 places
    b.bankFileName = fileName;
    b.cb.setFileName(fileName);
    b.changed = false;
    saveRecentBankFileList();
    return b;
}

From source file:com.socrata.datasync.ui.MetadataJobTab.java

public void saveJob() {
    populateJobFromFields();//  w  w w. j  a  va2s .  c o  m

    // TODO If an existing file was selected WARN user of overwriting

    // if first time saving this job: Open dialog box to select "Save as..." location
    // otherwise save to existing file
    boolean updateJobCommandTextField = false;
    String selectedJobFileLocation = jobFileLocation;
    if (selectedJobFileLocation.equals("")) {
        JFileChooser savedJobFileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                JOB_FILE_NAME + " (*." + JOB_FILE_EXTENSION + ")", JOB_FILE_EXTENSION);
        savedJobFileChooser.setFileFilter(filter);
        int returnVal = savedJobFileChooser.showSaveDialog(mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = savedJobFileChooser.getSelectedFile();
            selectedJobFileLocation = file.getAbsolutePath();
            if (!selectedJobFileLocation.endsWith("." + JOB_FILE_EXTENSION)) {
                selectedJobFileLocation += "." + JOB_FILE_EXTENSION;
            }
            jobFileLocation = selectedJobFileLocation;
            metadataJob.setPathToSavedFile(selectedJobFileLocation);
            jobTabTitleLabel.setText(metadataJob.getJobFilename());
            updateJobCommandTextField = true;
        }
    }
    // actually save the job file (may overwrite)
    try {
        metadataJob.writeToFile(selectedJobFileLocation);

        // Update job tab title label
        jobTabTitleLabel.setText(metadataJob.getJobFilename());

        // Update the textfield with new command
        if (updateJobCommandTextField) {
            String runJobCommand = Utils.getRunJobCommand(metadataJob.getPathToSavedFile());
            runCommandTextField.setText(runJobCommand);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(mainFrame,
                "Error saving " + selectedJobFileLocation + ": " + e.getMessage());
    }
}

From source file:edu.synth.SynthHelper.java

public String openDialogFileChooser(String path, boolean dirOnly, String name, String button,
        String filterType) {/*w ww .j  av  a  2 s.c  om*/
    JFileChooser fileOpen = new JFileChooser();
    if (!path.isEmpty())
        fileOpen.setCurrentDirectory(new File(path));
    else
        fileOpen.setCurrentDirectory(new File("."));
    if (dirOnly)
        fileOpen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    else {
        fileOpen.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        switch (filterType) {
        case "abn":
            FileFilter filter = new FileNameExtensionFilter("*.abn - Abundances file", "abn");
            fileOpen.setFileFilter(filter);
            break;
        case "model":
            filter = new FileNameExtensionFilter("*.atl - Kurucz's format model file", "atl");
            fileOpen.setFileFilter(filter);
            break;
        case "lns":
            filter = new FileNameExtensionFilter("*.lns - Lines file", "lns");
            fileOpen.setFileFilter(filter);
            break;
        }
    }
    fileOpen.setDialogTitle(name);
    fileOpen.setApproveButtonText(button);
    int returnVal = fileOpen.showOpenDialog(fileOpen);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File selectedPath = fileOpen.getSelectedFile();
        if (selectedPath != null)
            return selectedPath.getAbsolutePath();
    }
    return "";
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

public void showImportDialog() {
    String path = null;//from  ww  w.  j  av a 2  s. co  m
    if (resourcesDir != null) {
        path = resourcesDir.toString();
    }
    JFileChooser fc = new JFileChooser(path);
    fc.setDialogTitle(MessageBundle.get("dialogs.import.title"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setFileFilter(new FileNameExtensionFilter("json i18n file", "json"));
    int result = fc.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        importResources(Paths.get(fc.getSelectedFile().getPath()));
    }
}

From source file:colectordedatos.resultados.java

private void Exportar_a_ExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Exportar_a_ExcelActionPerformed
    if (jTable1.getRowCount() > 0) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos de excel", "xls");
        chooser.setFileFilter(filter);//  ww  w .j  av  a2  s.com
        chooser.setDialogTitle("Guardar archivo");
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            List<JTable> tb = new ArrayList<JTable>();
            List<String> nom = new ArrayList<String>();
            tb.add(jTable1);
            nom.add("Reporte de Errores");
            String file = chooser.getSelectedFile().toString().concat(".xls");
            try {
                exportaraexcel e = new exportaraexcel(new File(file), tb, nom);
                if (e.export()) {
                    JOptionPane.showMessageDialog(null,
                            "Los datos fueron exportados a excel en el directorio seleccionado",
                            "Mensaje de Informacion", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Hubo un error " + e.getMessage(), " Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "No hay datos para exportar", "Mensaje de error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.opendoorlogistics.studio.scripts.editor.ScriptEditor.java

protected SimpleAction createSaveScriptAsAction() {
    return new SimpleAction("Save as", "Save script as", "document-save-as-2-16x16.png") {

        @Override//from   w  w w  .  j  a  v  a2s .  c o m
        public void actionPerformed(ActionEvent e) {
            validateScriptData();

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new FileNameExtensionFilter(
                    AppConstants.ORG_NAME + " script  (" + ScriptConstants.FILE_EXT.toLowerCase() + ")",
                    ScriptConstants.FILE_EXT));
            File file = ScriptEditor.this.file;
            if (file == null) {
                file = createDefaultFilename();
            }

            if (file == null) {
                file = PreferencesManager.getSingleton().getScriptsDirectory();
            }

            // ensure absolute
            if (file != null) {
                file = file.getAbsoluteFile();
            }

            // ensure have filename
            if (file != null && file.isDirectory()) {
                file = new File(file, createDefaultPathlessFilename());
            }

            if (file != null) {
                chooser.setCurrentDirectory(file.getParentFile());
                chooser.setSelectedFile(file);
            }

            if (chooser.showSaveDialog(ScriptEditor.this) == JFileChooser.APPROVE_OPTION) {
                save(chooser.getSelectedFile());
            }
        }
    };
}

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

public ExistingFileChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new ExistingFileChooserDialog(findRegisteredWindowIfAny(), appProps,
                SOURCE_FOLDER) {/*from  www  .  j a va 2s  .  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: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);/*from   w w  w.  j  a  va 2  s.  co  m*/
    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
        {
            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.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSavePatchAs(SpinCADPatch p) {
    // Create a file chooser
    String savedPath = prefs.get("MRUPatchFolder", "");
    final JFileChooser fc = new JFileChooser(savedPath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("SpinCAD Files", "spcd");
    fc.setFileFilter(filter);/*from  w w w  .ja  v a2  s .com*/
    fc.setSelectedFile(new File(p.patchFileName));
    int returnVal = fc.showSaveDialog(new JFrame());
    // need to process user canceling box right here
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        // In response to a button click:
        File fileToBeSaved = fc.getSelectedFile();

        if (!fileToBeSaved.getAbsolutePath().endsWith(".spcd")) {
            fileToBeSaved = new File(fc.getSelectedFile() + ".spcd");
        }
        int n = JOptionPane.YES_OPTION;
        if (fileToBeSaved.exists()) {
            JFrame frame = new JFrame();
            n = JOptionPane.showConfirmDialog(frame, "Would you like to overwrite it?", "File already exists!",
                    JOptionPane.YES_NO_OPTION);
        }
        if (n == JOptionPane.YES_OPTION) {
            try {
                String filePath = fileToBeSaved.getPath();
                String fileName = fileToBeSaved.getName();
                p.patchFileName = fileName;
                fileSavePatch(p);
                recentPatchFileList.add(fileToBeSaved);
                saveMRUPatchFolder(filePath);

            } catch (Exception e) { // thrown over in SpinCADFile.java
                e.printStackTrace();
                SpinCADDialogs.MessageBox("File save failed!", "look at stack trace for info");
            } finally {
                p.setChanged(false);
            }
        }
    }
}

From source file:au.org.ala.delta.intkey.ui.DefineButtonDialog.java

@Action
public void DefineButtonDialog_Browse() {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(fileFilterDescription,
            new String[] { "bmp", "png" });
    chooser.setFileFilter(filter);//w  ww. j a  va 2 s .c o  m

    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        _txtFldFileName.setText(selectedFile.getAbsolutePath());
    }
}