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:ec.util.chart.swing.Charts.java

public static void saveChart(@Nonnull ChartPanel chartPanel) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileFilter defaultFilter = new FileNameExtensionFilter("PNG (.png)", "png");
    fileChooser.addChoosableFileFilter(defaultFilter);
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG (.jpg) (.jpeg)", "jpg", "jpeg"));
    if (Charts.canWriteChartAsSVG()) {
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG (.svg)", "svg"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Compressed SVG (.svgz)", "svgz"));
    }/*from  ww w .  j  av a2  s . c  o m*/
    fileChooser.setFileFilter(defaultFilter);
    File currentDir = chartPanel.getDefaultDirectoryForSaveAs();
    if (currentDir != null) {
        fileChooser.setCurrentDirectory(currentDir);
    }
    if (fileChooser.showSaveDialog(chartPanel) == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try (OutputStream stream = Files.newOutputStream(file.toPath())) {
            writeChart(getMediaType(file), stream, chartPanel.getChart(), chartPanel.getWidth(),
                    chartPanel.getHeight());
        }
        chartPanel.setDefaultDirectoryForSaveAs(fileChooser.getCurrentDirectory());
    }
}

From source file:it.ferogrammer.ui.MainAppFrame.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    if (jPanel2.getComponentCount() == 1 && (jPanel2.getComponent(0) instanceof ElectropherogramChartPanel)) {
        ElectropherogramChartPanel chartPanel = (ElectropherogramChartPanel) jPanel2.getComponent(0);
        final JFileChooser fc = new JFileChooser();
        //            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(chartPanel);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (!file.getName().endsWith(".png")) {
                int extindex = file.getPath().indexOf('.') == -1 ? file.getPath().length()
                        : file.getPath().indexOf('.');
                file = new File(file.getPath().substring(0, extindex) + ".png");
            }//from  w ww .  j  a va2s  .c  o m
            try {
                ChartUtilities.saveChartAsPNG(file, chartPanel.getChart(), chartPanel.getWidth(),
                        chartPanel.getHeight());
            } catch (IOException ex) {
                JOptionPane op = new JOptionPane();
                op.showMessageDialog(jPanel2, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane op = new JOptionPane();
        op.showMessageDialog(jPanel2, "Cannot export image", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:ImageIOTest.java

/**
 * Save the current image in a file/*  w ww .ja  v a2  s. c o  m*/
 * @param formatName the file format
 */
public void saveFile(final String formatName) {
    if (images == null)
        return;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatName);
    ImageWriter writer = iter.next();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = writer.getOriginatingProvider().getFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));

    int r = chooser.showSaveDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    try {
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(f);
        writer.setOutput(imageOut);

        writer.write(new IIOImage(images[0], null, null));
        for (int i = 1; i < images.length; i++) {
            IIOImage iioImage = new IIOImage(images[i], null, null);
            if (writer.canInsertImage(i))
                writer.writeInsert(i, iioImage, null);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
}

From source file:net.sf.clichart.main.ChartFrame.java

private void saveChart() {
    JFileChooser chooser = new JFileChooser(".");
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".jpg", "JPEG files"));
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".png", "PNG files"));

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

        if (outputFile.exists()) {
            int result = JOptionPane.showConfirmDialog(this, "File exists - overwrite?", "File exists",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result != JOptionPane.OK_OPTION) {
                return;
            }//from   w  w  w. ja  v  a 2s .  c  o  m
        }

        System.err.println("Saving chart to " + outputFile.getPath());
        try {
            new ChartSaver(m_chart, m_initialWidth, m_initialHeight).saveChart(outputFile);
        } catch (ChartSaverException e) {
            JOptionPane.showMessageDialog(this, "Failed to save chart: " + e.getMessage());
        }
    }
}

From source file:test.integ.be.fedict.performance.util.PerformanceResultDialog.java

public PerformanceResultDialog(PerformanceResultsData data) {

    super((Frame) null, "Performance test results");
    setSize(1000, 800);//from   ww  w  . j  ava2s. c o m

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    JMenuItem savePerformanceMenuItem = new JMenuItem("Save Performance");
    fileMenu.add(savePerformanceMenuItem);
    savePerformanceMenuItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save as PNG...");
            int result = fileChooser.showSaveDialog(PerformanceResultDialog.this);
            if (JFileChooser.APPROVE_OPTION == result) {
                File file = fileChooser.getSelectedFile();
                try {
                    ChartUtilities.saveChartAsPNG(file, performanceChart, 1024, 768);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "error saving to file: " + e.getMessage());
                }
            }
        }

    });
    JMenuItem saveMemoryMenuItem = new JMenuItem("Save Memory");
    fileMenu.add(saveMemoryMenuItem);
    saveMemoryMenuItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent event) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save as PNG...");
            int result = fileChooser.showSaveDialog(PerformanceResultDialog.this);
            if (JFileChooser.APPROVE_OPTION == result) {
                File file = fileChooser.getSelectedFile();
                try {
                    ChartUtilities.saveChartAsPNG(file, memoryChart, 1024, 768);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, "error saving to file: " + e.getMessage());
                }
            }
        }

    });

    // memory chart
    memoryChart = getMemoryChart(data.getIntervalSize(), data.getMemory());

    // performance chart
    performanceChart = getPerformanceChart(data.getIntervalSize(), data.getPerformance(),
            data.getExpectedRevokedCount());

    Container container = getContentPane();
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    if (null != performanceChart) {
        splitPane.setTopComponent(new ChartPanel(performanceChart));
    }
    if (null != memoryChart) {
        splitPane.setBottomComponent(new ChartPanel(memoryChart));
    }
    splitPane.setDividerLocation(getHeight() / 2);
    splitPane.setDividerSize(1);
    container.add(splitPane);

    setVisible(true);
}

From source file:de.stefanwndelmann.zy1270logger.ZY1270LoggerMain.java

private void saveCSVButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCSVButtonActionPerformed
    // TODO add your handling code here:
    String data = getCSVData();/*from   www.  ja  va 2  s  .c  om*/
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try (FileWriter fw = new FileWriter(chooser.getSelectedFile() + ".csv")) {
            fw.write(data);
        } catch (IOException ex) {
            Logger.getLogger(ZY1270LoggerMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.petersoft.advancedswing.enhancedtextarea.EnhancedTextArea.java

private void jSaveButtonActionPerformed(ActionEvent evt) {
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        CommonLib.saveFile(this.jTextArea.getText(), file);
    }/*from w ww . java  2  s.  c o m*/
}

From source file:JuliaSet3.java

public void save() throws IOException {
    // Find a factory object for printing Printable objects to PostScript.
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    String format = "application/postscript";
    StreamPrintServiceFactory factory = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
            format)[0];//from www  . ja  v  a 2s.co m

    // Ask the user to select a file and open the selected file
    JFileChooser chooser = new JFileChooser();
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    FileOutputStream out = new FileOutputStream(f);

    // Obtain a PrintService that prints to that file
    StreamPrintService service = factory.getPrintService(out);

    // Do the printing with the method below
    printToService(service, null);

    // And close the output file.
    out.close();
}

From source file:chibi.gemmaanalysis.cli.deprecated.ProbeMapperGui.java

/**
 * @return javax.swing.JButton/*from  w  w w  .ja va  2  s .  c  om*/
 */
private JButton getOutputFileBrowseButton() {
    if (outputFileBrowseButton == null) {
        outputFileBrowseButton = new JButton();
        outputFileBrowseButton.setText("Browse...");
        outputFileBrowseButton.setBounds(454, 4, 87, 26);

        outputFileBrowseButton.addActionListener(new ActionListener() {
            @Override
            @SuppressWarnings({ "synthetic-access" })
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.showSaveDialog(jContentPane.getParent());
                File selectedFile = fc.getSelectedFile();
                if (selectedFile != null) {
                    getOutputFileNameTextField().setText(selectedFile.getAbsolutePath());
                    if (selectedFile.canRead()) {
                        outputFile = selectedFile;
                    } else {
                        // error
                    }
                }
            }
        });
    }
    return outputFileBrowseButton;
}

From source file:com.intuit.tank.proxy.settings.ui.ProxyConfigDialog.java

private void save(int port, boolean followRedirecs, String outputFile,
        Set<ConfigInclusionExclusionRule> inclusions, Set<ConfigInclusionExclusionRule> exclusions,
        Set<ConfigInclusionExclusionRule> bodyInclusions, Set<ConfigInclusionExclusionRule> bodyExclusions,
        String configFileName) {/*w  w  w. jav  a2  s . com*/
    String fileName = "";
    if (StringUtils.isEmpty(configFileName)) {
        JFileChooser fileChooser = new JFileChooser();
        File file = new File(".");
        fileChooser.setCurrentDirectory(file);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setFileFilter(new XmlFileFilter());
        int showSaveDialog = fileChooser.showSaveDialog(this);
        if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
            String selectedFile = fileChooser.getSelectedFile().getName();
            if (!selectedFile.endsWith(".xml")) {
                selectedFile = selectedFile + ".xml";
            }
            fileName = fileChooser.getSelectedFile().getParent() + "/" + selectedFile;
            configHandler.setConfigFile(fileName);
        } else {
            return;
        }
    } else {
        fileName = configFileName;
    }
    CommonsProxyConfiguration.save(port, followRedirecs, outputFile, inclusions, exclusions, bodyInclusions,
            bodyExclusions, fileName);
    getProxyConfigPanel().update();
    configHandler.setConfigFile(fileName);
}