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.jax.maanova.plot.SaveChartAction.java

/**
 * {@inheritDoc}//from w w  w  .j av a2s  .co  m
 */
public void actionPerformed(ActionEvent e) {
    JFreeChart myChart = this.chart;
    Dimension mySize = this.size;

    if (myChart == null || mySize == null) {
        LOG.severe("Failed to save graph image because of a null value");
        MessageDialogUtilities.errorLater(Maanova.getInstance().getApplicationFrame(),
                "Internal error: Failed to save graph image.", "Image Save Failed");
    } else {
        // use the remembered starting dir
        MaanovaApplicationConfigurationManager configurationManager = MaanovaApplicationConfigurationManager
                .getInstance();
        JMaanovaApplicationState applicationState = configurationManager.getApplicationState();
        FileType rememberedJaxbImageDir = applicationState.getRecentImageExportDirectory();
        File rememberedImageDir = null;
        if (rememberedJaxbImageDir != null && rememberedJaxbImageDir.getFileName() != null) {
            rememberedImageDir = new File(rememberedJaxbImageDir.getFileName());
        }

        // select the image file to save
        JFileChooser fileChooser = new JFileChooser(rememberedImageDir);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Save Graph");
        fileChooser.setDialogTitle("Save Graph as Image");
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.addChoosableFileFilter(PngFileFilter.getInstance());
        fileChooser.setFileFilter(PngFileFilter.getInstance());
        int response = fileChooser.showSaveDialog(Maanova.getInstance().getApplicationFrame());
        if (response == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            // tack on the extension if there isn't one
            // already
            if (!PngFileFilter.getInstance().accept(selectedFile)) {
                String newFileName = selectedFile.getName() + "." + PngFileFilter.PNG_EXTENSION;
                selectedFile = new File(selectedFile.getParentFile(), newFileName);
            }

            if (selectedFile.exists()) {
                // ask the user if they're sure they want to overwrite
                String message = "Exporting the graph image to " + selectedFile.getAbsolutePath()
                        + " will overwrite an " + " existing file. Would you like to continue anyway?";
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine(message);
                }

                boolean overwriteOk = MessageDialogUtilities
                        .confirmOverwrite(Maanova.getInstance().getApplicationFrame(), selectedFile);
                if (!overwriteOk) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("overwrite canceled");
                    }
                    return;
                }
            }

            try {
                ChartUtilities.saveChartAsPNG(selectedFile, myChart, mySize.width, mySize.height);

                File parentDir = selectedFile.getParentFile();
                if (parentDir != null) {
                    // update the "recent image directory"
                    ObjectFactory objectFactory = new ObjectFactory();
                    FileType latestJaxbImageDir = objectFactory.createFileType();
                    latestJaxbImageDir.setFileName(parentDir.getAbsolutePath());
                    applicationState.setRecentImageExportDirectory(latestJaxbImageDir);
                }
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "failed to save graph image", ex);
            }
        }
    }
}

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

/**
 * Prompts for a file using the file chooser dialog
 * //from w w w  .jav a 2  s.  c  o m
 * @param fileExtensions
 *            Accepted file extensions - must be null if filePrefixes is
 *            non-null
 * @param filePrefixes
 *            Accepted file prefixes - must be null if fileExtensions is
 *            non-null
 * @param description
 *            Description of the acceptable files
 * @param createFileIfNonExistant
 *            if true, the file will be created if it does not exist. Also,
 *            the system's "save" will be used instead of the "open" dialog.
 * @param startBrowseDirectory
 *            The directory that the file chooser should start in
 * @param parent
 *            parent component for the file chooser
 * @return the selected file, or null if no file was selected.
 * @throws IOException
 */
public static File promptForFile(List<String> fileExtensions, List<String> filePrefixes,
        final String description, boolean createFileIfNonExistant, File startBrowseDirectory, Component parent)
        throws IOException {
    if (fileExtensions != null && filePrefixes != null) {
        throw new IllegalArgumentException(
                "Only one of the file extensions or file prefixes should be non-null");
    }

    JFileChooser chooser = new JFileChooser(startBrowseDirectory);
    FileFilter filter;

    if (fileExtensions != null) {
        String[] extensionsArray = new String[fileExtensions.size()];
        fileExtensions.toArray(extensionsArray);
        filter = new FileNameExtensionFilter(description, extensionsArray);
    } else {
        final String[] prefixesArray = new String[filePrefixes.size()];
        filePrefixes.toArray(prefixesArray);
        filter = new FileFilter() {

            @Override
            public String getDescription() {
                return description;
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                } else {
                    return StringUtils.startsWithAny(f.getName(), prefixesArray);
                }
            }
        };
    }
    chooser.setFileFilter(filter);

    int returnVal;

    if (createFileIfNonExistant) {
        returnVal = chooser.showSaveDialog(parent);
    } else {
        returnVal = chooser.showOpenDialog(parent);
    }

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        if (createFileIfNonExistant) {
            File file = chooser.getSelectedFile();

            if (!file.exists()) {
                // if only one file extension was supplied and the filename
                // does
                // not end with this extension, add it before
                // creating the file
                if (fileExtensions.size() == 1) {
                    String extension = fileExtensions.get(0);
                    String filePath = chooser.getSelectedFile().getAbsolutePath();
                    if (!filePath.endsWith(extension)) {
                        file = new File(filePath + "." + extension);
                    }
                }

                file.createNewFile();
            }
            return file;
        } else {
            return chooser.getSelectedFile();
        }
    } else {
        return null;
    }
}

From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cancelButton) {
        this.setVisible(false);
        this.dispose();
    } else if (e.getSource() == saveChartButton) {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog/*from  w w  w.ja  v a  2  s. co  m*/
                .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)"));
        saveFileDialog.addChoosableFileFilter(
                new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)"));
        saveFileDialog
                .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)"));
        int save = saveFileDialog.showSaveDialog(this);
        if (save == JFileChooser.APPROVE_OPTION) {
            File file = saveFileDialog.getSelectedFile();
            int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue();
            int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue();

            ExtensionFileFilter filter = null;
            try {
                filter = (ExtensionFileFilter) saveFileDialog.getFileFilter();
                if (!filter.hasExtension(file)) {
                    file = filter.appendExtension(file);
                }
            } catch (ClassCastException ex) {
                // Try to infer the type of file by its extension
                FileFilter[] filters = saveFileDialog.getChoosableFileFilters();
                for (int i = 0; i < filters.length; ++i) {
                    if (filters[i] instanceof ExtensionFileFilter) {
                        filter = (ExtensionFileFilter) filters[i];
                        if (filter.hasExtension(file)) {
                            break;
                        }
                        filter = null;
                    }
                }

                if (filter == null) {
                    // Could not infer the type
                    JOptionPane.showMessageDialog(null,
                            "File type not specified!\nWhen giving file name, please also select one of the supported file types.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            // Save the chart to the specified file name
            try {
                String ext = filter.getExtension();
                if (ext.equals("jpeg")) {
                    ChartUtilities.saveChartAsJPEG(file, chart, width, height);
                } else if (ext.equals("png")) {
                    ChartUtilities.saveChartAsPNG(file, chart, width, height);
                } else {
                    VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height));
                    graphics.startExport();
                    chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height));
                    graphics.endExport();
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            this.setVisible(false);
            this.dispose();
        } else if (save == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.martus.client.swingui.FxInSwingMainWindow.java

protected File showFileSaveDialog(String title, File directory, Vector<FormatFilter> filters) {
    while (true) {
        JFileChooser fileChooser = createFileChooser(title, directory, filters);

        int userResult = fileChooser.showSaveDialog(getCurrentActiveFrame().getSwingFrame());
        if (userResult != JFileChooser.APPROVE_OPTION)
            return null;

        File selectedFile = fileChooser.getSelectedFile();

        FormatFilter selectedFilter = (FormatFilter) fileChooser.getFileFilter();
        selectedFile = getFileWithExtension(selectedFile, selectedFilter.getExtension());

        if (!selectedFile.exists())
            return selectedFile;

        if (confirmDlg(getCurrentActiveFrame().getSwingFrame(), "OverWriteExistingFile"))
            return selectedFile;

        directory = selectedFile.getParentFile();
    }//  ww w .  j  a va  2  s  . c o m
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveTSV() {
    JFileChooser chooser = new JFileChooser("Save evaluation result as TSV");
    chooser.setCurrentDirectory(frame.defaultDirectory);
    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && (JOptionPane.showConfirmDialog(frame,
                "File already exists. Overwrite?") != JOptionPane.YES_OPTION)) {
            return;
        }//from w  w w  . j  a  v  a  2  s  . c  om
        frame.saveTSV(chooser.getSelectedFile());
    }
}

From source file:gov.nij.er.ui.EntityResolutionDemo.java

private void saveParameters() {
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new SerializedParameterFileFilter());
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {// www .  jav  a 2  s .c om
            saveParameters(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:table.TablePanel.java

public String doSaveAs(File f) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Image Files", "png");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);//  w w  w .j  a  v a 2 s. com
    String filename = "";
    int option = fileChooser.showSaveDialog(this.parent);
    if (option == JFileChooser.APPROVE_OPTION) {
        filename = fileChooser.getSelectedFile().getPath();
        if (!filename.endsWith(".png")) {
            filename = filename + ".png";
        }
        saveTableAsPNG(new File(filename), this.table, parent.getWidth(), parent.getHeight());
    }
    return filename;
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveXML() {
    JFileChooser chooser = new JFileChooser("Save evaluation result as alignment XML");
    chooser.setCurrentDirectory(frame.defaultDirectory);
    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && (JOptionPane.showConfirmDialog(frame,
                "File already exists. Overwrite?") != JOptionPane.YES_OPTION)) {
            return;
        }/*  w  ww .j  a  v  a  2 s .co m*/
        try {
            frame.saveXML(chooser.getSelectedFile(), SaveXMLMode.SAVE_EVERYTHING);
        } catch (JDOMException | IOException e) {
            JOptionPane.showConfirmDialog(frame, e, "Error saving XML", JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:pl.dpbz.poid.zadanie4.gui.GUI.java

private void saveJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveJButtonActionPerformed
    // TODO save sound to file
    JFileChooser fc = new JFileChooser();
    fc.showSaveDialog(this);
    String path = fc.getSelectedFile().getAbsolutePath();
    path += ".wav";
    SamplesToWave saver;/* w  w  w  .j  av a 2  s  .  c  o  m*/

    if (this.wahWahJRadioButton.isSelected()) {
        saver = new SamplesToWave(44100, this.filterWahWah.getOutputSignal(), this.af);

    } else {
        saver = new SamplesToWave(SOIFilter.SAMPLING_FREQUENCY, this.filter.getOutputSignal(), this.af);
    }

    try {
        saver.saveWave(path);
    } catch (IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Zapisane");

}

From source file:net.sf.profiler4j.console.Console.java

/**
 * Saves the current project./*ww w . j a va2 s  .  co m*/
 * 
 * @param saveAs force the user to select a file name even
 * @return <code>true</code> if the user has cancelled (only in the case of save as)
 */
public boolean saveProject(boolean saveAs) {
    if (project.getFile() == null || saveAs) {
        JFileChooser fc = new JFileChooser(lastDir);

        fc.setDialogTitle("Save Project As");

        fc.addChoosableFileFilter(projectFilter);
        if (fc.showSaveDialog(mainFrame) == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            if (!f.getName().endsWith(".p4j")) {
                f = new File(f.getAbsolutePath() + ".p4j");
            }
            project.setFile(f);
        } else {
            return true;
        }
    }

    Element rootEl = new Element("Profiler4jProject");
    Document doc = new Document(rootEl);

    rootEl.addContent(new Element("Host").setText(project.getHostname()));
    rootEl.addContent(new Element("Port").setText(String.valueOf(project.getPort())));

    Element rulesEl = new Element("Rules");
    rootEl.addContent(rulesEl);

    rulesEl.setAttribute("access", project.getAccess().name());
    rulesEl.setAttribute("beanProps", String.valueOf(project.isBeanprops()));

    for (Rule rule : project.getRules()) {
        rulesEl.addContent(
                new Element("Rule").setText(rule.getPattern()).setAttribute("action", rule.getAction().name()));
    }

    Element exportPatternEl = new Element(PROJECT_XML_ELEMENT__EXPORT_PATTERN);
    String enabled = String.valueOf(project.isExportAutomaticallyEnabled());
    exportPatternEl.setAttribute(PROJECT_XML_ATTRIBUTE__ENABLED, enabled);
    exportPatternEl.setAttribute(PROJECT_XML_ATTRIBUTE__PATTERN, project.getExportPattern());
    rootEl.addContent(exportPatternEl);

    try {
        FileWriter fw = new FileWriter(project.getFile());
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(doc, fw);
        fw.close();
        project.clearChanged();
    } catch (IOException e) {
        error("I/O Error", e);
    }
    return false;
}