Example usage for javax.swing JFileChooser showSaveDialog

List of usage examples for javax.swing JFileChooser showSaveDialog

Introduction

In this page you can find the example usage for javax.swing JFileChooser showSaveDialog.

Prototype

public int showSaveDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up a "Save File" file chooser dialog.

Usage

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  av a  2  s . c  o  m
        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());
    }
}

From source file:org.yccheok.jstock.gui.Utils.java

private static File promptSaveJFileChooser(String suggestedFileName,
        FileNameExtensionFilter... fileNameExtensionFilters) {
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    final JFileChooser chooser = new JFileChooser(jStockOptions.getLastFileIODirectory());
    chooser.setAcceptAllFileFilterUsed(false);
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        chooser.addChoosableFileFilter(fileNameExtensionFilter);
    }//w  w  w . j  ava2  s. c  o m
    chooser.setSelectedFile(new File(suggestedFileName));
    final java.util.Map<String, FileNameExtensionFilter> map = new HashMap<String, FileNameExtensionFilter>();
    for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
        map.put(fileNameExtensionFilter.getDescription(), fileNameExtensionFilter);
    }
    final FileNameExtensionFilter filter = map.get(jStockOptions.getLastSavedFileNameExtensionDescription());
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    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);
        boolean found = false;
        root: for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
            String[] extensions = fileNameExtensionFilter.getExtensions();
            for (String e : extensions) {
                if (e.equals(extension)) {
                    found = true;
                    break root;
                }
            }
        }
        if (!found) {
            for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
                String[] extensions = fileNameExtensionFilter.getExtensions();
                if (extensions.length <= 0) {
                    continue;
                }
                final String e = extensions[0];
                if (chooser.getFileFilter().getDescription().equals(fileNameExtensionFilter.getDescription())) {
                    if (e.startsWith(".")) {
                        file = new File(file.getAbsolutePath() + e);
                    } else {
                        file = new File(file.getAbsolutePath() + "." + e);
                    }
                    break;
                }
            }
        }
        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);
        }
        final String e = Utils.getFileExtension(file);
        for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
            String[] extensions = fileNameExtensionFilter.getExtensions();
            if (extensions.length <= 0) {
                continue;
            }
            if (e.equals(extensions[0])) {
                jStockOptions.setLastFileNameExtensionDescription(fileNameExtensionFilter.getDescription());
                break;
            }
        }
        return file;
    }
}

From source file:org.zaproxy.zap.extension.ascan.PolicyManagerDialog.java

private JButton getExportButton() {
    if (this.exportButton == null) {
        this.exportButton = new JButton(Constant.messages.getString("ascan.policymgr.button.export"));
        this.exportButton.setEnabled(false);
        this.exportButton.addActionListener(new ActionListener() {
            @Override/*from ww  w  . ja va2  s . c  om*/
            public void actionPerformed(ActionEvent e) {
                String name = (String) getParamsModel().getValueAt(getParamsTable().getSelectedRow(), 0);
                if (name != null) {
                    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
                    File file = new File(Constant.getZapHome(), name + PolicyManager.POLICY_EXTENSION);
                    chooser.setSelectedFile(file);

                    chooser.setFileFilter(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            if (file.isDirectory()) {
                                return true;
                            } else if (file.isFile() && file.getName().endsWith(".policy")) {
                                return true;
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Constant.messages.getString("file.format.zap.policy");
                        }
                    });
                    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
                    if (rc == JFileChooser.APPROVE_OPTION) {
                        file = chooser.getSelectedFile();
                        if (file == null) {
                            return;
                        }
                        try {
                            ScanPolicy policy = extension.getPolicyManager().getPolicy(name);
                            if (policy != null) {
                                extension.getPolicyManager().exportPolicy(policy, file);
                            }
                        } catch (ConfigurationException e1) {
                            logger.error(e1.getMessage(), e1);
                            View.getSingleton()
                                    .showWarningDialog(Constant.messages.getString("ascan.policy.load.error"));
                        }
                    }
                }
            }
        });
    }
    return this.exportButton;
}

From source file:org.zaproxy.zap.extension.beanshell.BeanShellConsoleFrame.java

private JButton getBtnSave() {
    if (btnSave == null) {
        btnSave = new JButton();
        btnSave.setText(Constant.messages.getString("beanshell.button.save"));

        btnSave.addActionListener(new ActionListener() {
            @Override/* w w w .  ja  v  a2  s  .  co  m*/
            public void actionPerformed(ActionEvent e) {
                if (currentScriptFile != null) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), currentScriptFile);
                        getBeanShellPanel().setSaved(true);
                    } catch (IOException ex) {
                        log.error(ex.getMessage(), ex);
                        View.getSingleton().showWarningDialog(
                                Constant.messages.getString("beanshell.error.message.saving.script"));
                    }

                } else {
                    JFileChooser fc = new JFileChooser(scriptsDir);
                    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    int result = fc.showSaveDialog(getBeanShellPanel());

                    if (result == JFileChooser.APPROVE_OPTION) {
                        try {
                            saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                            getBeanShellPanel().setSaved(true);
                            currentScriptFile = fc.getSelectedFile();
                        } catch (IOException ex) {
                            log.error(ex.getMessage(), ex);
                            View.getSingleton().showWarningDialog(
                                    Constant.messages.getString("beanshell.error.message.saving.script"));
                        }
                    }
                }
            }
        });
    }
    return btnSave;
}

From source file:org.zaproxy.zap.extension.beanshell.BeanShellConsoleFrame.java

private JButton getBtnSaveAs() {
    if (btnSaveAs == null) {
        btnSaveAs = new JButton();
        btnSaveAs.setText(Constant.messages.getString("beanshell.button.saveas"));

        btnSaveAs.addActionListener(new ActionListener() {
            @Override/*from   ww  w  . j a  v  a2  s . c o  m*/
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser(scriptsDir);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int result = fc.showSaveDialog(getBeanShellPanel());
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                        getBeanShellPanel().setSaved(true);
                        currentScriptFile = fc.getSelectedFile();
                    } catch (IOException ex) {
                        log.error(ex.getMessage(), ex);
                        View.getSingleton().showWarningDialog(
                                Constant.messages.getString("beanshell.error.message.saving.script"));
                    }
                }
            }
        });
    }
    return btnSaveAs;
}

From source file:org.zaproxy.zap.extension.compare.ExtensionCompare.java

private File getOutputFile() {

    JFileChooser chooser = new JFileChooser(getModel().getOptionsParam().getUserDirectory());
    chooser.setFileFilter(new FileFilter() {
        @Override/*w  w w . j a v  a  2 s. com*/
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().toLowerCase().endsWith(".htm")) {
                return true;
            } else if (file.isFile() && file.getName().toLowerCase().endsWith(".html")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("file.format.html");
        }
    });

    File file = null;
    int rc = chooser.showSaveDialog(getView().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return file;
        }
        getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileNameLc = file.getAbsolutePath().toLowerCase();
        if (!fileNameLc.endsWith(".htm") && !fileNameLc.endsWith(".html")) {
            file = new File(file.getAbsolutePath() + ".html");
        }
        return file;

    }
    return file;
}

From source file:org.zaproxy.zap.extension.customFire.CustomFireDialog.java

/**
 * Saves custom vectors tab/*  w w w .j  ava 2s  .  c  om*/
 * @param list
 * @param httpRequest void `
 */
protected void saveCustomVectors(ArrayList list, String httpRequest) {

    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Custom Vectors.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }

        ArrayList woi = new ArrayList<>();
        woi.add(list);
        woi.add(httpRequest);

        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(woi);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveCV.success"));

        } catch (IOException e1) {
            e1.printStackTrace();
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveCV.error"));
            return;
        }
    }
}

From source file:org.zaproxy.zap.extension.customFire.CustomFireDialog.java

/**
 * Saves input vectors tab//from   w  w  w  . j a va2s  .  c o m
 * @param scannerParam void `
 */
protected void saveScannerParam(ScannerParam scannerParam) {

    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Input Vectors.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(scannerParam);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveIV.success"));

        } catch (IOException e1) {
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveIV.error"));
            return;
        }
    }
    if (rc == JFileChooser.CANCEL_OPTION) {
        chooser.setVisible(false);
        return;
    }
}

From source file:org.zaproxy.zap.extension.customFire.PolicyManagerDialog.java

private JButton getExportButton() {
    if (this.exportButton == null) {
        this.exportButton = new JButton(
                Constant.messages.getString("customFire.custom.policymgr.button.export"));
        this.exportButton.setEnabled(false);
        this.exportButton.addActionListener(new ActionListener() {
            @Override/*from   w ww . j av a  2 s.c  o  m*/
            public void actionPerformed(ActionEvent e) {
                String name = (String) getParamsModel().getValueAt(getParamsTable().getSelectedRow(), 0);
                if (name != null) {
                    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
                    File file = new File(Constant.getZapHome(), name + PolicyManager.POLICY_EXTENSION);
                    chooser.setSelectedFile(file);

                    chooser.setFileFilter(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            if (file.isDirectory()) {
                                return true;
                            } else if (file.isFile() && file.getName().endsWith(".policy")) {
                                return true;
                            }
                            return false;
                        }

                        @Override
                        public String getDescription() {
                            return Constant.messages.getString("file.format.zap.policy");
                        }
                    });
                    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
                    if (rc == JFileChooser.APPROVE_OPTION) {
                        file = chooser.getSelectedFile();
                        if (file == null) {
                            return;
                        }
                        try {
                            CustomScanPolicy policy = extension.getPolicyManager().getPolicy(name);
                            if (policy != null) {
                                extension.getPolicyManager().exportPolicy(policy, file);
                            }
                        } catch (ConfigurationException e1) {
                            logger.error(e1.getMessage(), e1);
                            View.getSingleton().showWarningDialog(
                                    Constant.messages.getString("customFire.custom.policy.load.error"));
                        }
                    }
                }
            }
        });
    }
    return this.exportButton;
}

From source file:org.zaproxy.zap.extension.customFire.TechnologyTreePanel.java

/**
 * To save tech settings/*from  w w  w. j  a  va 2  s .c  o  m*/
 *  void `
 */
public void saveTechState() {

    //Do Tech ser
    JFileChooser chooser = new JFileChooser(Constant.getPoliciesDir());
    File file = new File(Constant.getZapHome(), "Tech.ser");
    chooser.setSelectedFile(file);

    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".ser")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("customFire.custom.file.format.csp.ser");
        }
    });
    int rc = chooser.showSaveDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        try {

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(TechnologyTreePanel.this);
            oos.close();
            fos.close();
            View.getSingleton()
                    .showMessageDialog(Constant.messages.getString("customFire.custom.ser.saveTech.success"));

        } catch (IOException e1) {
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("customFire.custom.ser.saveTech.error"));
            return;
        }
    }
    if (rc == JFileChooser.CANCEL_OPTION) {
        chooser.setVisible(false);
        return;
    }

}