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.colombbus.tangara.CommandSelection.java

/**
 * Enables to save the program  in a file (step 2 of save or step 3 of create program)
 * @return/*from w  ww .j a  v a 2s.com*/
 *       the path of the saved file
 */
private File saveFile() {
    File destinationFile = null;
    JFileChooser fileChooser = createFileChooser();
    int userChoice = fileChooser.showSaveDialog(this);
    if (userChoice == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        destinationFile = buildDestFile(selectedFile);

        if (destinationFile.exists() && userConfirmOverride(destinationFile) == false) {
            return null;
        }

        try {
            saveBufferToFile(destinationFile);
            succeedSavingFile(fileChooser, destinationFile);
        } catch (Throwable th) {
            failSavingFile(destinationFile, th);
        }
    }
    return destinationFile;
}

From source file:org.colombbus.tangara.net.FileReceptionDialog.java

private void setTargetFile() {
    File targetDir = Configuration.instance().getUserHome();
    JFileChooser chooserDlg = new JFileChooser(targetDir);

    String filterMsg = Messages.getString("FileReceptionDialog.filter.allFiles");
    SimpleFileFilter filter = new SimpleFileFilter(filterMsg);
    chooserDlg.setFileFilter(filter);/* w w  w  .j a  va  2 s  .  c  o  m*/

    File originalSelFile = new File(targetDir, sourceFilename);
    File curSelFile = originalSelFile;
    boolean showDialog = true;
    while (showDialog) {
        chooserDlg.setSelectedFile(curSelFile);
        int userAction = chooserDlg.showSaveDialog(owner);
        curSelFile = chooserDlg.getSelectedFile();
        switch (userAction) {
        case JFileChooser.CANCEL_OPTION:
            showDialog = false;
            break;
        case JFileChooser.APPROVE_OPTION:
            if (curSelFile.exists()) {
                String title = Messages.getString("FileReceptionDialog.overwrite.title");
                String msgPattern = Messages.getString("FileReceptionDialog.overwrite.message");
                String overwriteMsg = MessageFormat.format(msgPattern, curSelFile.getName());
                Object[] options = { Messages.getString("FileReceptionDialog.yes"),
                        Messages.getString("FileReceptionDialog.no") };
                int userChoice = JOptionPane.showOptionDialog(owner, overwriteMsg, title,
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a
                        // custom Icon
                        options, // the titles of buttons
                        options[0]);
                if (userChoice == JOptionPane.OK_OPTION) {
                    if (saveFileAs(curSelFile)) {
                        showDialog = false;
                    }
                }
            } else if (saveFileAs(curSelFile)) {
                showDialog = false;
            }
            break;
        case JFileChooser.ERROR_OPTION:
            LOG.error("Error in file chooser dialog");
            // TODO what to do in case of error ? Retry ?
            showDialog = false;
            break;
        }
    }
}

From source file:org.domainmath.gui.MainFrame.java

/**
 * Save script as another name./*from w ww .  j  a  v  a  2  s .c  o m*/
 */
public void saveScriptAs() {
    JFileChooser fc = new JFileChooser();
    fc.setMultiSelectionEnabled(false);
    fc.setDialogTitle("Save As");

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String oldfile = fileTab.getToolTipTextAt(fileTab.getSelectedIndex());
        save(fc.getSelectedFile(), fileTab.getSelectedIndex());
        this.removeFileNameFromList(oldfile);
        fileTab.setToolTipTextAt(fileTab.getSelectedIndex(), fc.getSelectedFile().getAbsolutePath());
        this.addFileNameToList(fc.getSelectedFile().getAbsolutePath());
    }

}

From source file:org.domainmath.gui.MainFrame.java

public void saveHistoryAs() {
    JFileChooser fc = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("M-Files  (*.m)", "m");
    fc.setCurrentDirectory(new File(System.getProperty("user.dir") + File.separator + "works"));
    fc.setFileFilter(filter);//from w w  w . j  a v  a  2s . c  o  m
    fc.setMultiSelectionEnabled(false);

    fc.setDialogTitle("Save As");
    File file_save;
    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String path = fc.getSelectedFile().getAbsolutePath();
        if (!path.endsWith(".m")) {
            file_save = new File(fc.getSelectedFile().getAbsolutePath() + ".m");
            saveHistory(file_save);
        } else {
            file_save = new File(fc.getSelectedFile().getAbsolutePath() + ".m");
            saveHistory(file_save);
        }

    }
}

From source file:org.domainmath.gui.MainFrame.java

public void saveplot() {
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(System.getProperty("user.dir") + File.separator + "works"));
    fc.setFileFilter(DomainMathFileFilter.SAVE_PLOT_FILE_FILTER);
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);/* w  ww .ja  v  a2 s.co  m*/

    File file_plot;
    String name;
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        System.err.println(fc.getFileFilter().getDescription());
        file_plot = fc.getSelectedFile();
        name = file_plot.getName();
        evaluateWithOutput("saveas(1," + "'" + file_plot.getAbsolutePath() + "');");

    }
}

From source file:org.drugis.mtc.gui.GeneratedCodeWindow.java

private JButton createSaveButton() {
    JButton saveButton = new JButton("Save", MainWindow.IMAGELOADER.getIcon("savefile.gif"));
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int returnVal = chooser.showSaveDialog(GeneratedCodeWindow.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    if (!file.isDirectory()) {
                        JOptionPane.showMessageDialog(GeneratedCodeWindow.this,
                                "Error: please select a directory to save to", "Files could not be saved.",
                                JOptionPane.ERROR_MESSAGE);
                    }//w w  w.  j  a  v a 2 s  .com
                    writeFiles(file);
                    JOptionPane.showMessageDialog(GeneratedCodeWindow.this,
                            "Your files have been saved to: \n" + file.getPath(), "Files saved.",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(GeneratedCodeWindow.this, "Error: " + e.getMessage(),
                        "Files could not be saved.", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    return saveButton;
}

From source file:org.evors.rs.ui.frames.PopulationViewer.java

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(UIUtils.getUserDir("/user/"));
    int result = fc.showSaveDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {

        PrintWriter out = null;/*from w w  w .j  a  v  a  2s  . co m*/
        try {
            FileUtils.copyFile(new File(exp.getLayout().getFilename()),
                    new File(fc.getSelectedFile().getParent() + "layout.json"));
            FileUtils.copyFile(new File(exp.getWorld().getFilename()),
                    new File(fc.getSelectedFile().getParent() + "world.json"));
            JSONPopulation pop = ((PopulationTM) jTable1.getModel()).getPop();
            out = new PrintWriter(fc.getSelectedFile());
            out.print(pop.toJSONString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PopulationViewer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PopulationViewer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }
}

From source file:org.f2o.absurdum.puck.gui.PuckFrame.java

/**
 * "Save As..." functionality//from   ww w.  java2s  . c o  m
 */
public boolean saveAs() throws Exception {
    JFileChooser jfc = new JFileChooser(".");
    FiltroFicheroMundo filter = new FiltroFicheroMundo();
    jfc.setFileFilter(filter);
    int opt = jfc.showSaveDialog(PuckFrame.this);
    if (opt == JFileChooser.APPROVE_OPTION) {
        File f = jfc.getSelectedFile();

        if (jfc.getFileFilter() == filter && !filter.acceptFilename(f)) {
            String fileName = f.getAbsolutePath();
            fileName += ".agw";
            f = new File(fileName);
        }

        saveToFile(f);
        editingFileName = f.toString();
        refreshTitle();
        addRecentFile(f);
        return true;
    } else
        return false;
}

From source file:org.fhaes.gui.ShapeFileDialog.java

/**
 * Prompt the user for an output filename
 * // w  w w .j a v a2 s. c  om
 * @param filter
 * @return
 */
private File getOutputFile(FileFilter filter) {

    String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_EXPORT_FOLDER, null);
    File outputFile;

    // Create a file chooser
    final JFileChooser fc = new JFileChooser(lastVisitedFolder);

    fc.setAcceptAllFileFilterUsed(true);

    if (filter != null) {
        fc.addChoosableFileFilter(filter);
        fc.setFileFilter(filter);
    }

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    fc.setDialogTitle("Save as...");

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

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

        if (FileUtils.getExtension(outputFile.getAbsolutePath()) == "") {
            log.debug("Output file extension not set by user");

            if (fc.getFileFilter().getDescription().equals(new SHPFileFilter().getDescription())) {
                log.debug("Adding shp extension to output file name");
                outputFile = new File(outputFile.getAbsolutePath() + ".shp");
            }
        } else {
            log.debug("Output file extension set my user to '"
                    + FileUtils.getExtension(outputFile.getAbsolutePath()) + "'");
        }

        App.prefs.setPref(PrefKey.PREF_LAST_EXPORT_FOLDER, outputFile.getAbsolutePath());
    } else {
        return null;
    }

    if (outputFile.exists()) {
        Object[] options = { "Overwrite", "No", "Cancel" };
        int response = JOptionPane.showOptionDialog(this,
                "The file '" + outputFile.getName() + "' already exists.  Are you sure you want to overwrite?",
                "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a custom Icon
                options, // the titles of buttons
                options[0]); // default button title

        if (response != JOptionPane.YES_OPTION) {
            return null;
        }
    }

    return outputFile;
}

From source file:org.freeplane.features.url.mindmapmode.ExportBranchAction.java

public void actionPerformed(final ActionEvent e) {
    final NodeModel existingNode = Controller.getCurrentModeController().getMapController().getSelectedNode();
    final Controller controller = Controller.getCurrentController();
    final MapModel parentMap = controller.getMap();
    if (parentMap == null || existingNode == null || existingNode.isRoot()) {
        controller.getViewController().err("Could not export branch.");
        return;//from  w w  w .j av a2 s .  com
    }
    if (parentMap.getFile() == null) {
        controller.getViewController().out("You must save the current map first!");
        ((MModeController) Controller.getCurrentModeController()).save();
    }
    JFileChooser chooser;
    final File file = parentMap.getFile();
    if (file == null) {
        return;
    }
    chooser = new JFileChooser(file.getParentFile());
    chooser.setSelectedFile(
            new File(createFileName(TextController.getController().getShortText(existingNode))));
    if (((MFileManager) UrlManager.getController()).getFileFilter() != null) {
        chooser.addChoosableFileFilter(((MFileManager) UrlManager.getController()).getFileFilter());
    }
    final int returnVal = chooser.showSaveDialog(controller.getViewController().getContentPane());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        final String ext = FileUtils.getExtension(chosenFile.getName());
        if (!ext.equals(org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION_WITHOUT_DOT)) {
            chosenFile = new File(chosenFile.getParent(),
                    chosenFile.getName() + org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION);
        }
        try {
            Compat.fileToUrl(chosenFile);
        } catch (final MalformedURLException ex) {
            UITools.errorMessage(TextUtils.getText("invalid_url"));
            return;
        }
        if (chosenFile.exists()) {
            final int overwriteMap = JOptionPane.showConfirmDialog(
                    controller.getMapViewManager().getMapViewComponent(),
                    TextUtils.getText("map_already_exists"), "Freeplane", JOptionPane.YES_NO_OPTION);
            if (overwriteMap != JOptionPane.YES_OPTION) {
                return;
            }
        }
        /*
         * Now make a copy from the node, remove the node from the map and
         * create a new Map with the node as root, store the new Map, add
         * the copy of the node to the parent, and set a link from the copy
         * to the new Map.
         */
        final NodeModel parent = existingNode.getParentNode();
        final File oldFile = parentMap.getFile();

        final URI newUri = LinkController.toLinkTypeDependantURI(oldFile, chosenFile);
        final URI oldUri = LinkController.toLinkTypeDependantURI(chosenFile, file);
        ((MLinkController) LinkController.getController()).setLink(existingNode, oldUri,
                LinkController.LINK_ABSOLUTE);
        final int nodePosition = parent.getChildPosition(existingNode);
        final ModeController modeController = Controller.getCurrentModeController();
        modeController.undoableResolveParentExtensions(LogicalStyleKeys.NODE_STYLE, existingNode);
        final MMapController mMapController = (MMapController) modeController.getMapController();
        mMapController.deleteNode(existingNode);
        {
            final IActor actor = new IActor() {
                private final boolean wasFolded = existingNode.isFolded();

                public void undo() {
                    PersistentNodeHook.removeMapExtensions(existingNode);
                    existingNode.setMap(parentMap);
                    existingNode.setFolded(wasFolded);
                }

                public String getDescription() {
                    return "ExportBranchAction";
                }

                public void act() {
                    existingNode.setParent(null);
                    existingNode.setFolded(false);
                    mMapController.newModel(existingNode);
                }
            };
            Controller.getCurrentModeController().execute(actor, parentMap);
        }
        final MapModel map = existingNode.getMap();
        IExtension[] oldExtensions = map.getRootNode().getSharedExtensions().values()
                .toArray(new IExtension[] {});
        for (final IExtension extension : oldExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.removeExtension(clazz);
            }
        }
        final Collection<IExtension> newExtensions = parentMap.getRootNode().getSharedExtensions().values();
        for (final IExtension extension : newExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.addExtension(extension);
            }
        }
        ((MFileManager) UrlManager.getController()).save(map, chosenFile);
        final NodeModel newNode = mMapController.addNewNode(parent, nodePosition, existingNode.isLeft());
        ((MTextController) TextController.getController()).setNodeText(newNode, existingNode.getText());
        modeController.undoableCopyExtensions(LogicalStyleKeys.NODE_STYLE, existingNode, newNode);
        map.getFile();
        ((MLinkController) LinkController.getController()).setLink(newNode, newUri,
                LinkController.LINK_ABSOLUTE);
        map.destroy();
    }
}