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:Main.Interface_Main.java

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    System.out.print(serialData);

    //Create a file chooser
    final JFileChooser fc = new JFileChooser();
    FileFilter ft = new FileNameExtensionFilter("Comma Seperated Value (*.csv)", "csv");
    fc.setFileFilter(ft);// w  w  w  .  j av a2 s . com

    //In response to a button click:
    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        System.out.println(file);

        try {
            /*BufferedWriter writer = null;
            writer = new BufferedWriter(new FileWriter(file + ".csv")); //add .txt?
            writer.write("time, amp, max, min, volt, max, min, wattage, mah, mwh, dp, dm");
            writer.newLine();
            for (int i = 0; i < csvData.size(); i++){
            //String serialStringData = csvData.toString();
            writer.write(csvData.get(i).toString());
            writer.newLine();
            }
            writer.close( );
            */
            File sFile = new File(logTmpFile);

            Files.copy(sFile.toPath(), file.toPath());

            JOptionPane.showMessageDialog(this, "Data exported successfully!", "Success!",
                    JOptionPane.INFORMATION_MESSAGE);
        } catch (java.io.IOException e) {

            JOptionPane.showMessageDialog(this, e);

        }

    } else {
        System.out.println("Save Canceled");
    }

}

From source file:com.mgmtp.perfload.loadprofiles.ui.AppFrame.java

private File showSaveDialog(final JFileChooser fc, final File file, final String extension) {
    fc.setSelectedFile(file);// w  ww. j a va  2  s  .co  m
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fc.getSelectedFile();
        if (!FilenameUtils.getExtension(selectedFile.getName()).equalsIgnoreCase(extension)) {
            selectedFile = new File(selectedFile.getParentFile(), selectedFile.getName() + "." + extension);
        }

        if (selectedFile.exists()) {
            String msg = String.format("The file '%s' already exists. Overwrite?", selectedFile);
            switch (JOptionPane.showConfirmDialog(this, msg)) {
            case JOptionPane.YES_OPTION:
                return selectedFile;
            case JOptionPane.NO_OPTION:
                return showSaveDialog(fc, file, extension);
            default:
                return null;
            }
        }
        return selectedFile;
    }
    return null;
}

From source file:ca.canucksoftware.clockthemebuilder.ThemeBuilderView.java

private File loadFileChooser(javax.swing.filechooser.FileFilter ff, String saveName) {
    File result;//from w  w  w  .j a  v  a2  s  .c  om
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    fc.setMultiSelectionEnabled(false);
    if (ff != null) {
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(ff);
    } else {
        fc.setAcceptAllFileFilterUsed(true);
    }
    if (saveName == null) {
        fc.setDialogTitle("");
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    } else {
        fc.setDialogTitle("Save As...");
        fc.setSelectedFile(new File(saveName));
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
        } else {
            result = null;
        }
    }
    return result;
}

From source file:com.freedomotic.jfrontend.MainWindow.java

private void mnuSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSaveAsActionPerformed

    final JFileChooser fc = new JFileChooser(Info.PATHS.PATH_DATA_FOLDER + "/furn/");
    int returnVal = fc.showSaveDialog(this);

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

        try {/*from   w ww .  j  a v  a 2 s.c  om*/
            master.getApi().environments().saveEnvironmentsToFolder(folder);

        } catch (Exception ex) {
            LOG.error(ex.getMessage());
        }
    } else {
        LOG.info(i18n.msg("canceled_by_user"));
    }
}

From source file:fll.scheduler.SchedulerUI.java

void saveScheduleDescription() {
    if (null == mScheduleDescriptionFile) {
        // prompt the user for a filename to save to

        final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null);

        final JFileChooser fileChooser = new JFileChooser();
        final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)",
                new String[] { "properties" });
        fileChooser.setFileFilter(filter);
        if (null != startingDirectory) {
            fileChooser.setCurrentDirectory(new File(startingDirectory));
        }//from   ww w .  jav  a  2  s.  c  om

        final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            final File currentDirectory = fileChooser.getCurrentDirectory();
            PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath());

            mScheduleDescriptionFile = fileChooser.getSelectedFile();
            mDescriptionFilename.setText(mScheduleDescriptionFile.getName());
        } else {
            // user canceled
            return;
        }
    }

    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile),
            Utilities.DEFAULT_CHARSET)) {
        final SolverParams params = mScheduleDescriptionEditor.getParams();
        final List<String> errors = params.isValid();
        if (!errors.isEmpty()) {
            final String formattedErrors = errors.stream().collect(Collectors.joining("\n"));
            JOptionPane.showMessageDialog(SchedulerUI.this,
                    "There are errors that need to be corrected before the description can be saved: "
                            + formattedErrors,
                    "Error saving file", JOptionPane.ERROR_MESSAGE);
        } else {
            final Properties properties = new Properties();
            params.save(properties);
            properties.store(writer, null);
        }
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error saving file: %s", e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:net.sf.nmedit.nomad.core.Nomad.java

public void fileSave(boolean saveAs) {
    Document d = pageContainer.getSelection();
    if (d == null)
        return;/*from   w  ww. jav  a2  s.  c  o m*/

    if (!saveAs) {
        Iterator<FileService> iter = ServiceRegistry.getServices(FileService.class);
        FileService useService = null;
        while (iter.hasNext()) {
            FileService fs = iter.next();
            if (fs.isDirectSaveOperationSupported(d)) {
                useService = fs;
                break;
            }
        }

        if (useService != null) {
            useService.save(d, useService.getAssociatedFile(d));
            return;
        }
    }

    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(lastSaveInFolderLocation);
    chooser.setMultiSelectionEnabled(false);

    Iterator<FileService> iter = ServiceRegistry.getServices(FileService.class);
    while (iter.hasNext()) {
        FileService fs = iter.next();

        boolean add = (saveAs && fs.isSaveOperationSupported(d))
                || ((!saveAs) && fs.isDirectSaveOperationSupported(d));

        if (add)
            chooser.addChoosableFileFilter(fs.getFileFilter());
    }

    File sfile = d.getFile();
    if (sfile == null && d.getTitle() != null)
        sfile = new File(d.getTitle());
    if (sfile != null)
        chooser.setSelectedFile(sfile);

    if (!(chooser.showSaveDialog(mainWindow) == JFileChooser.APPROVE_OPTION))
        return;

    FileService service = FileServiceTool.lookupFileService(chooser);

    if (service != null) {
        File newFile = chooser.getSelectedFile();
        if (newFile == null)
            return;

        if (newFile.exists() && JOptionPane.showConfirmDialog(mainWindow,
                "Overwrite existing file '" + newFile.getAbsolutePath() + "' ?", "File already exists.",
                JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
            return;

        service.save(d, newFile);

        lastSaveInFolderLocation = newFile.getParentFile();
    } else {
        JOptionPane.showMessageDialog(mainWindow, "Could not find service to save file.");
    }
}

From source file:org.gumtree.vis.awt.CompositePanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format./*from   w w w.ja  v  a  2s  .c  o  m*/
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    String currentDirectory = System.getProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL);
    if (currentDirectory != null) {
        File savePath = new File(currentDirectory);
        if (savePath.exists() && savePath.isDirectory()) {
            fileChooser.setCurrentDirectory(savePath);
        }
    }
    ExtensionFileFilter pngFilter = new ExtensionFileFilter("PNG_Image_Files", ".png");
    ExtensionFileFilter jpgFilter = new ExtensionFileFilter("JPG_Image_Files", ".jpg");
    fileChooser.addChoosableFileFilter(pngFilter);
    fileChooser.addChoosableFileFilter(jpgFilter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        String selectedDescription = fileChooser.getFileFilter().getDescription();
        String fileExtension = StaticValues.DEFAULT_IMAGE_FILE_EXTENSION;
        if (selectedDescription.toLowerCase().contains("png")) {
            fileExtension = "png";
            if (!filename.toLowerCase().endsWith(".png")) {
                filename = filename + ".png";
            }
        } else if (selectedDescription.toLowerCase().contains("jpg")) {
            fileExtension = "jpg";
            if (!filename.toLowerCase().endsWith(".jpg")) {
                filename = filename + ".jpg";
            }
        }
        File selectedFile = new File(filename);
        int confirm = JOptionPane.YES_OPTION;
        if (selectedFile.exists()) {
            confirm = JOptionPane.showConfirmDialog(this, selectedFile.getName() + " exists, overwrite?",
                    "Confirm Overwriting", JOptionPane.YES_NO_OPTION);
        }
        if (confirm == JOptionPane.YES_OPTION) {
            saveTo(filename, fileExtension);
            System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL, fileChooser.getSelectedFile().getParent());
        }
    }
}

From source file:com.opendoorlogistics.studio.AppFrame.java

@SuppressWarnings("serial")
private List<MyAction> initFileActions() {
    ArrayList<MyAction> ret = new ArrayList<>();
    ret.add(new MyAction("New", "Create new file", null, "document-new-6.png", false,
            KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK)) {

        @Override/*w ww. j  a  v a2s .  c  o m*/
        public void actionPerformed(ActionEvent e) {
            createNewDatastore();
        }
    });

    ret.add(new MyAction("Open", "Open file", null, "document-open-3.png", false,
            KeyStroke.getKeyStroke(KeyEvent.VK_O, java.awt.Event.CTRL_MASK)) {

        @Override
        public void actionPerformed(ActionEvent e) {
            openDatastoreWithUserPrompt();
        }
    });

    ret.add(null);

    ret.add(new MyAction("Close", "Close file", null, "document-close-4.png", true,
            KeyStroke.getKeyStroke(KeyEvent.VK_W, java.awt.Event.CTRL_MASK)) {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (!canCloseDatastore()) {
                return;
            }
            closeDatastore();
        }
    });

    ret.add(null);

    ret.add(new MyAction("Save", "Save file", null, "document-save-2.png", true,
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK)) {

        @Override
        public void actionPerformed(ActionEvent e) {
            saveDatastoreWithoutUserPrompt(loaded.getLastFile());
        }

        @Override
        public void updateEnabled() {

            setEnabled(loaded != null && loaded.getLastFile() != null);
        }

    });
    ret.add(new MyAction("Save as", "Save file as", null, "document-save-as-2.png", true,
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK | Event.ALT_MASK)) {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = SupportedFileType.EXCEL.createFileChooser();
            if (loaded.getLastFile() != null) {
                chooser.setSelectedFile(loaded.getLastFile());
            } else {
                File file = PreferencesManager.getSingleton().getFile(PrefKey.LAST_IO_DIR);
                IOUtils.setFile(file, chooser);
            }
            if (chooser.showSaveDialog(AppFrame.this) == JFileChooser.APPROVE_OPTION) {
                saveDatastoreWithoutUserPrompt(chooser.getSelectedFile());
            }

        }
    });

    return ret;
}

From source file:net.panthema.BispanningGame.GamePanel.java

public void writePdf() throws FileNotFoundException, DocumentException {

    // Query user for filename
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Specify PDF file to save");
    chooser.setCurrentDirectory(new File("."));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf");
    chooser.setFileFilter(filter);/* w w w.jav a2 s  .c om*/

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;

    File outfile = chooser.getSelectedFile();
    if (!outfile.getAbsolutePath().endsWith(".pdf")) {
        outfile = new File(outfile.getAbsolutePath() + ".pdf");
    }

    // Calculate page size rectangle
    Dimension size = mVV.getSize();
    Rectangle rsize = new Rectangle(size.width, size.height);

    // Open the PDF file for writing - and create a Graphics2D object
    Document document = new Document(rsize);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outfile));
    document.open();

    PdfContentByte contentByte = writer.getDirectContent();
    PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, size.width, size.height, new DefaultFontMapper());

    // Create a container to hold the visualization
    Container container = new Container();
    container.addNotify();
    container.add(mVV);
    container.setVisible(true);
    container.paintComponents(graphics2d);

    // Dispose of the graphics and close the document
    graphics2d.dispose();
    document.close();

    // Put mVV back onto visible plane
    setLayout(new BorderLayout());
    add(mVV, BorderLayout.CENTER);
}

From source file:net.panthema.BispanningGame.GamePanel.java

public void writeGraphML() throws IOException {

    // Query user for filename
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Specify GraphML file to save");
    chooser.setCurrentDirectory(new File("."));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("GraphML File", "graphml");
    chooser.setFileFilter(filter);//  www.jav a  2 s. c om

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;

    File outfile = chooser.getSelectedFile();
    if (!outfile.getAbsolutePath().endsWith(".graphml")) {
        outfile = new File(outfile.getAbsolutePath() + ".graphml");
    }

    // construct graphml writer
    GraphMLWriter<Integer, MyEdge> graphWriter = new GraphMLWriter<Integer, MyEdge>();

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outfile)));

    graphWriter.addVertexData("x", null, "0", new Transformer<Integer, String>() {
        public String transform(Integer v) {
            return Double.toString(mLayout.getX(v));
        }
    });

    graphWriter.addVertexData("y", null, "0", new Transformer<Integer, String>() {
        public String transform(Integer v) {
            return Double.toString(mLayout.getY(v));
        }
    });

    graphWriter.addEdgeData("color", null, "0", new Transformer<MyEdge, String>() {
        public String transform(MyEdge e) {
            return Integer.toString(e.color);
        }
    });

    graphWriter.save(mGraph, out);
}