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:org.signserver.admin.gui.AddWorkerDialog.java

private void filePathBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filePathBrowseButtonActionPerformed
    final JFileChooser chooser = new JFileChooser();
    final File baseDir = SignServerAdminGUIApplication.getBaseDir();
    final String basedirPath = baseDir.getAbsolutePath();
    final File sampleDir = new File(basedirPath + File.separator + "doc" + File.separator + "sample-configs");

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setCurrentDirectory(sampleDir.isDirectory() ? sampleDir : baseDir);
    chooser.setFileFilter(new FileNameExtensionFilter("Properties files", "properties"));

    final int res = chooser.showOpenDialog(this);

    if (res == JFileChooser.APPROVE_OPTION) {
        final File file = chooser.getSelectedFile();
        filePathTextField.setText(file.getAbsolutePath());
        fileSelected = true;//from   ww  w.  j  av a  2 s . c o  m
    }

    updateControls();
}

From source file:org.signserver.admin.gui.ViewCertificateFrame.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (certificate != null) {
        final JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        final FileFilter pemFilter = new FileNameExtensionFilter("X.509 Certificate (PEM)", "pem");
        final FileFilter pemChainFilter = new FileNameExtensionFilter("X.509 Certificate with chain (PEM)",
                "pem");
        final FileFilter derFilter = new FileNameExtensionFilter("X.509 Certificate (DER)", "cer", "crt",
                "der");
        chooser.addChoosableFileFilter(pemFilter);
        chooser.addChoosableFileFilter(derFilter);
        chooser.addChoosableFileFilter(pemChainFilter);
        chooser.setDialogTitle("Save certificate as file");

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

            try {
                if (chooser.getFileFilter() == derFilter) {
                    // DER file
                    FileUtils.writeByteArrayToFile(file, certificate.getEncoded());
                } else {
                    // PEM file
                    BufferedOutputStream out = null;
                    try {
                        out = new BufferedOutputStream(new FileOutputStream(file));
                        PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(out));
                        if (chooser.getFileFilter() == pemFilter) {
                            pemWriter.writeObject(certificate);
                        } else {
                            for (X509Certificate cert : certificates) {
                                pemWriter.writeObject(cert);
                            }//from ww w  .  ja v  a2 s . c om
                        }
                        pemWriter.close();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this,
                        "Exporting certificate failed:\n" + ex.getLocalizedMessage(), "Export",
                        JOptionPane.ERROR_MESSAGE);
            } catch (CertificateEncodingException ex) {
                JOptionPane.showMessageDialog(this,
                        "Unable to encode certificate:\n" + ex.getLocalizedMessage(), "Export",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:org.sleuthkit.autopsy.modules.hashdatabase.HashDbImportDatabaseDialog.java

private void initFileChooser() {
    fileChooser.setDragEnabled(false);//from   w w w.  j  ava  2  s . c o  m
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    String[] EXTENSION = new String[] { "txt", "kdb", "idx", "hash", "Hash", "hsh" }; //NON-NLS
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            NbBundle.getMessage(this.getClass(), "HashDbImportDatabaseDialog.fileNameExtFilter.text"),
            EXTENSION);
    fileChooser.setFileFilter(filter);
    fileChooser.setMultiSelectionEnabled(false);
}

From source file:org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.java

private String searchForFile() {
    String filePath = null;/*  w  w  w.  j  a  v  a 2s .co m*/
    JFileChooser fc = new JFileChooser();
    fc.setDragEnabled(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    String[] EXTENSION = new String[] { "txt", "idx", "hash", "Hash", "kdb" }; //NON-NLS
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            NbBundle.getMessage(this.getClass(), "HashDbManager.fileNameExtensionFilter.title"), EXTENSION);
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        try {
            filePath = f.getCanonicalPath();
        } catch (IOException ex) {
            Logger.getLogger(HashDbManager.class.getName()).log(Level.WARNING,
                    "Couldn't get selected file path", ex); //NON-NLS
        }
    }
    return filePath;
}

From source file:org.tinymediamanager.ui.dialogs.BugReportDialog.java

/**
 * Instantiates a new feedback dialog./* w w w  . ja  va 2  s  . co  m*/
 */
public BugReportDialog() {
    super(BUNDLE.getString("BugReport"), "bugReportdialog");
    getContentPane().setLayout(new BorderLayout(0, 0));

    JPanel panelContent = new JPanel();
    getContentPane().add(panelContent, BorderLayout.CENTER);
    panelContent.setLayout(new FormLayout(
            new ColumnSpec[] { FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
                    FormSpecs.DEFAULT_COLSPEC, FormSpecs.LABEL_COMPONENT_GAP_COLSPEC,
                    ColumnSpec.decode("default:grow"), FormSpecs.RELATED_GAP_COLSPEC,
                    ColumnSpec.decode("default:grow"), FormSpecs.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
                    FormSpecs.UNRELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"),
                    FormSpecs.LABEL_COMPONENT_GAP_ROWSPEC, RowSpec.decode("default:grow"),
                    FormSpecs.UNRELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, FormSpecs.UNRELATED_GAP_ROWSPEC,
                    RowSpec.decode("default:grow"), FormSpecs.UNRELATED_GAP_ROWSPEC, }));

    final JTextArea taDescription = new JTextArea();
    taDescription.setOpaque(false);
    taDescription.setWrapStyleWord(true);
    taDescription.setLineWrap(true);
    taDescription.setEditable(false);
    taDescription.setText(BUNDLE.getString("BugReport.description")); //$NON-NLS-1$
    panelContent.add(taDescription, "2, 2, 6, 1, fill, fill");

    final JButton btnSaveLogs = new JButton(BUNDLE.getString("BugReport.createlogs")); //$NON-NLS-1$
    btnSaveLogs.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // open the log download window
            try {
                Path file = TmmUIHelper.saveFile(BUNDLE.getString("BugReport.savelogs"), "tmm_logs.zip", //$NON-NLS-1$
                        new FileNameExtensionFilter("Zip files", ".zip"));
                if (file != null) {
                    writeLogsFile(file.toFile());
                }
            } catch (Exception ex) {
                LOGGER.error("Could not write logs.zip: " + ex.getMessage());
            }
        }
    });

    final JLabel lblStep1 = new JLabel(BUNDLE.getString("BugReport.step1")); //$NON-NLS-1$
    panelContent.add(lblStep1, "2, 4, default, top");

    final JTextArea taStep1 = new JTextArea();
    taStep1.setText(BUNDLE.getString("BugReport.step1.description")); //$NON-NLS-1$
    taStep1.setOpaque(false);
    taStep1.setEditable(false);
    panelContent.add(taStep1, "5, 4, fill, fill");
    panelContent.add(btnSaveLogs, "7, 4");

    final JButton btnCreateIssue = new JButton(BUNDLE.getString("BugReport.craeteissue")); //$NON-NLS-1$
    btnCreateIssue.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // create the url for github
            String baseUrl = "https://github.com/tinyMediaManager/tinyMediaManager/issues/new?body=";
            String params = "Version: " + ReleaseInfo.getRealVersion();
            params += "\nBuild: " + ReleaseInfo.getRealBuildDate();
            params += "\nOS: " + System.getProperty("os.name") + " " + System.getProperty("os.version");
            params += "\nJDK: " + System.getProperty("java.version") + " " + System.getProperty("os.arch") + " "
                    + System.getProperty("java.vendor");
            params += "\n\n__What is the actual behaviour?__\n\n";
            params += "\n\n__What is the expected behaviour?__\n\n";
            params += "\n\n__Steps to reproduce:__\n\n";
            params += "\n\n__Additional__\nHave you attached the logfile from the day it happened?";

            String url = "";
            try {
                url = baseUrl + URLEncoder.encode(params, "UTF-8");
                TmmUIHelper.browseUrl(url);
            } catch (Exception e1) {
                LOGGER.error("FAQ", e1);
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, url, "message.erroropenurl",
                        new String[] { ":", e1.getLocalizedMessage() }));
            }
        }
    });

    final JLabel lblStep2 = new JLabel(BUNDLE.getString("BugReport.step2")); //$NON-NLS-1$
    panelContent.add(lblStep2, "2, 6, default, top");

    final JTextArea taStep2 = new JTextArea();
    taStep2.setOpaque(false);
    taStep2.setEditable(false);
    taStep2.setText(BUNDLE.getString("BugReport.step2.description")); //$NON-NLS-1$
    panelContent.add(taStep2, "5, 6, fill, fill");
    panelContent.add(btnCreateIssue, "7, 6");

    final JLabel lblHintIcon = new JLabel(IconManager.HINT);
    panelContent.add(lblHintIcon, "3, 8");

    final JLabel lblHint = new JLabel(BUNDLE.getString("BugReport.languagehint")); //$NON-NLS-1$
    panelContent.add(lblHint, "5, 8");

    JPanel panelButtons = new JPanel();

    getContentPane().add(panelButtons, BorderLayout.SOUTH);

    JButton btnClose = new JButton(BUNDLE.getString("Button.close")); //$NON-NLS-1$
    btnClose.setIcon(IconManager.CANCEL);
    btnClose.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    panelButtons.setLayout(new FormLayout(
            new ColumnSpec[] { ColumnSpec.decode("default:grow"), FormSpecs.DEFAULT_COLSPEC,
                    FormSpecs.RELATED_GAP_COLSPEC, },
            new RowSpec[] { FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("25px"),
                    FormSpecs.RELATED_GAP_ROWSPEC, }));
    panelButtons.add(btnClose, "2, 2");
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename./*from   w ww.j  a v  a2  s .  c  o  m*/
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Action entry points.//from   ww w  .  ja v a  2 s  . c om
 * <p>
 * All action entry points named with +ActionPerformed().
 */
public void onFileOpen() {
    final JFileChooser fc = new JFileChooser();
    File filePath = RuntimePreferences.getUserHome();
    fc.setCurrentDirectory(filePath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Project File(.tmpx)", "tmpx");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    final int returnVal = fc.showOpenDialog(parent);
    filePath = fc.getCurrentDirectory();
    RuntimePreferences.setUserHome(filePath);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        filePath = fc.getSelectedFile();

        if (filePath.getName().endsWith(".tmpx") && filePath.exists()) {
            try {
                final FileInputStream fr = new FileInputStream(filePath);
                fr.close();
                onOpenFile(filePath);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"),
                        getString("MSG.ERROR"), JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"), getString("MSG.ERROR"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.wandora.application.gui.topicpanels.ProcessingTopicPanel.java

@Override
public void init() {
    Wandora wandora = Wandora.getWandora();
    if (options == null) {
        if (USE_LOCAL_OPTIONS) {
            options = new Options(wandora.getOptions());
        } else {/*from w  ww.j a  v  a 2s. co m*/
            options = wandora.getOptions();
        }
    }
    tm = wandora.getTopicMap();

    initComponents();
    this.addComponentListener(this);
    try {
        // JavaSyntaxKit syntaxKit = new JavaSyntaxKit();
        // syntaxKit.install(processingEditor);
        DefaultSyntaxKit.initKit();
        processingEditor.setContentType("text/java");
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
    EditorKit ek=processingEditor.getEditorKit();
    if(ek instanceof DefaultSyntaxKit){
    DefaultSyntaxKit sk=(DefaultSyntaxKit)ek;
    sk.setProperty("Action.parenthesis", null); 
    sk.setProperty("Action.brackets", null);
    sk.setProperty("Action.quotes", null);
    sk.setProperty("Action.double-quotes", null);
    sk.setProperty("Action.close-curly", null);
    }*/
    readOptions();

    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK);
    processingEditor.getInputMap().put(key, "saveOperation");
    Action saveOperation = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            saveCurrentSketch();
        }
    };
    processingEditor.getActionMap().put("saveOperation", saveOperation);
    processingEditor.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n");

    innerPanel.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) {
            revalidate();
            Wandora.getWandora().validate();
        }

        @Override
        public void componentMoved(ComponentEvent e) {
            revalidate();
            Wandora.getWandora().validate();
        }

        @Override
        public void componentShown(ComponentEvent e) {
            revalidate();
            Wandora.getWandora().validate();
        }

        @Override
        public void componentHidden(ComponentEvent e) {
            revalidate();
            Wandora.getWandora().validate();
        }
    });

    if (currentSketch != null) {
        processingEditor.setText(currentSketch);
    } else {
        processingEditor.setText(defaultMessage);
    }

    FileNameExtensionFilter sketchFilter = new FileNameExtensionFilter("Processing sketch files", "sketch");
    fc = new JFileChooser();
    fc.setFileFilter(sketchFilter);
    fc.setCurrentDirectory(new File(sketchPath));
}

From source file:org.wso2.carbon.cluster.ui.ClusterWizard.java

private void btnZipFileSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZipFileSelectActionPerformed
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Zip File", "zip");
    chooser.setFileFilter(filter);/*from   ww w .  ja  va  2  s.  c om*/
    int returnVal = chooser.showOpenDialog(getParent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        zipAbsFilePath = chooser.getSelectedFile().getAbsolutePath();
        txtZipFilePath.setText(zipAbsFilePath);
        zipFileName = FilenameUtils.removeExtension(chooser.getSelectedFile().getName());
    }
}

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//from ww w .  j a v  a  2  s.com
        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());
    }
}