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.jcurl.demo.tactics.JCurlShotPlanner.java

/**
 * Render the current view into a <a/*from   w w  w .j ava 2s . c om*/
 * href="http://en.wikipedia.org/wiki/Svg">SVG</a>
 * image (File Menu Action).
 * 
 * @see BatikWrapper#renderSvg(Container, java.io.OutputStream)
 */
@Action(enabledProperty = "renderSvgAvailable", block = BlockingScope.ACTION)
public Task<Void, Void> fileExportSvg() {
    final JFileChooser fcSvg = createSvgChooser(getFile(), "exportSvgFileChooser");
    for (;;) {
        if (JFileChooser.APPROVE_OPTION != fcSvg.showSaveDialog(getMainFrame()))
            return null;
        final File dst = gui.ensureSuffix(fcSvg.getSelectedFile(), svgPat);
        if (!askOverwrite(dst))
            continue;

        return new WaitCursorTask<Void, Void>(this) {
            @Override
            protected Void doCursor() throws Exception {
                batik.renderSvg(tactics, dst);
                return null;
            }
        };
    }
}

From source file:org.jcurl.demo.tactics.JCurlShotPlanner.java

private File saveHelper(File dst, final File base, final String name, final boolean forceOverwrite) {
    JFileChooser fcJcx = null;
    for (;;) {/*  ww  w  .j  a  v  a2 s .  c  o  m*/
        if (fcJcx == null)
            fcJcx = createJcxChooser(base, name);
        if (dst == null) {
            if (JFileChooser.APPROVE_OPTION != fcJcx.showSaveDialog(getMainFrame()))
                return null;
            dst = fcJcx.getSelectedFile();
        }
        if (dst == null)
            continue;
        dst = gui.ensureSuffix(dst, jcxzPat);
        if (forceOverwrite || askOverwrite(dst))
            try {
                save(tactics.getCurves(), dst);
                return dst;
            } catch (final Exception e) {
                showErrorDialog("Couldn't save to '" + dst + "'", e);
            }
        else
            dst = null;
    }
}

From source file:org.jwebsocket.ui.TestDialog.java

/**
 *
 * @param aDefaultFilename//w  w w .  ja  v  a 2 s.  c  om
 */
public void saveLogs(String aDefaultFilename) {
    if (aDefaultFilename == null || aDefaultFilename.equals("")) {
        aDefaultFilename = "jWebSocketTests_" + new SimpleDateFormat("YYYY-MM-dd").format(new Date()) + ".log";
    }
    JFileChooser lChooser = new JFileChooser();
    FileNameExtensionFilter lFilter = new FileNameExtensionFilter("*.log files", "log");
    lChooser.setFileFilter(lFilter);
    lChooser.setSelectedFile(new File(aDefaultFilename));
    int lReturnVal = lChooser.showSaveDialog(this);
    if (lReturnVal == JFileChooser.APPROVE_OPTION) {
        FileWriter lWriter = null;
        try {
            File lFile = lChooser.getSelectedFile();
            lWriter = new FileWriter(lFile);
            lWriter.write(txaLog.getText());
        } catch (IOException aException) {
            mLog(aException.getMessage());
        } finally {
            try {
                if (lWriter != null) {
                    lWriter.close();
                }
            } catch (IOException aIoException) {
                mLog(aIoException.getMessage());
            }
        }
    }
}

From source file:org.kse.gui.dialogs.sign.DSignJar.java

private void outputJarBrowsePressed() {
    JFileChooser chooser = FileChooserFactory.getArchiveFileChooser();

    File currentFile = new File(jtfOutputJar.getText());

    if (currentFile.getParentFile() != null && currentFile.getParentFile().exists()) {
        chooser.setCurrentDirectory(currentFile.getParentFile());
        chooser.setSelectedFile(currentFile);
    } else {// www. j  a v a2 s  .  c  o m
        chooser.setCurrentDirectory(CurrentDirectory.get());
    }

    chooser.setDialogTitle(res.getString("DSignJar.ChooseOutputJar.Title"));

    chooser.setMultiSelectionEnabled(false);

    int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
            : chooser.showDialog(this, res.getString("DSignJar.OutputJarChooser.button"));
    if (rtnValue == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);
        jtfOutputJar.setText(chosenFile.toString());
        jtfOutputJar.setCaretPosition(0);
    }
}

From source file:org.kse.gui.dialogs.sign.DSignMidlet.java

private void outputJadBrowsePressed() {
    JFileChooser chooser = FileChooserFactory.getJadFileChooser();

    File currentFile = new File(jtfOutputJad.getText());

    if (currentFile.getParentFile() != null && currentFile.getParentFile().exists()) {
        chooser.setCurrentDirectory(currentFile.getParentFile());
        chooser.setSelectedFile(currentFile);
    } else {// w  w  w.  j av a  2  s .c o  m
        chooser.setCurrentDirectory(CurrentDirectory.get());
    }

    chooser.setDialogTitle(res.getString("DSignMidlet.ChooseOutputJad.Title"));

    chooser.setMultiSelectionEnabled(false);

    int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
            : chooser.showDialog(this, res.getString("DSignMidlet.OutputJadChooser.button"));
    if (rtnValue == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);
        jtfOutputJad.setText(chosenFile.toString());
        jtfOutputJad.setCaretPosition(0);
    }
}

From source file:org.kuali.test.creator.TestCreator.java

/**
 *
 * @param testHeader/*from   w w w .j  a v  a2s  .co m*/
 */
public void handleExportTest(TestHeader testHeader) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setSelectedFile(new File(Utils.formatForFileName(testHeader.getTestName()) + ".export"));
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();

        PrintWriter pw = null;

        try {
            pw = new PrintWriter(new FileWriter(file));
            Platform platform = (Platform) Utils.findPlatform(getConfiguration(), testHeader.getPlatformName())
                    .copy();

            platform.setEmailAddresses("");
            if (platform.getTestSuites() != null) {
                platform.getTestSuites().setTestSuiteArray(new TestSuite[0]);
            }

            if (platform.getPlatformTests() != null) {
                platform.getPlatformTests().setTestHeaderArray(new TestHeader[0]);
            }

            platform.setEmailAddresses("");
            platform.setDatabaseConnectionName("");

            pw.println("[test-platform]");
            pw.println(platform.toString().replace("xml-fragment", "test:platform"));
            pw.println();

            pw.println("[test-header]");
            pw.println(testHeader.toString().replace("xml-fragment", "test:test-header"));
            pw.println();

            pw.println("[test-desription]");
            File ftest = new File(Utils.getTestFilePath(getConfiguration(), testHeader));
            pw.println(Utils.getTestDescription(ftest));
            pw.println();

            pw.println("[test-operations]");
            pw.println(new String(FileUtils.readFileToByteArray(ftest)));
        }

        catch (Exception ex) {
            LOG.error(ex.toString(), ex);
            UIUtils.showError(this, "File Export Error",
                    "Error exporting file: " + file.getName() + " - " + ex.toString());
        }

        finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            }

            catch (Exception ex) {
            }
            ;
        }
    }
}

From source file:org.languagetool.gui.Main.java

private void saveFile(boolean newFile) {
    if (currentFile == null || newFile) {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileFilter(new PlainTextFileFilter());
        jfc.showSaveDialog(frame);

        File file = jfc.getSelectedFile();
        if (file == null) { // user clicked cancel
            return;
        }//from  ww w.j  a va2 s .c  o m
        currentFile = file;
        bom = null;
        updateTitle();
    }
    try {
        if (bom != null) {
            FileUtils.writeByteArrayToFile(currentFile, bom.getBytes());
            FileUtils.write(currentFile, textArea.getText(), bom.getCharsetName(), true);
        } else {
            FileUtils.write(currentFile, textArea.getText(), Charset.defaultCharset());
        }
    } catch (IOException ex) {
        Tools.showError(ex);
    }
}

From source file:org.mbs3.juniuploader.gui.pnlSettings.java

private void btnExportActionPerformed(ActionEvent evt) {
    final pnlSettings thisFrame = this;
    if (evt.getSource() == this.btnExport) {
        JFileChooser fc = new JFileChooser();
        //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int returnVal = fc.showSaveDialog(thisFrame);

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

            try {
                if (file != null && file.createNewFile()) {
                    log.debug("Writing all possible options to a file");
                    frmMain.storePreferences();
                    Prefs.flush();/*w  ww  .ja v  a2s .co  m*/
                    Prefs.exportFile(file);
                } else {
                    log.info("File chosen already exists, will not overwrite it");
                }
            } catch (Exception ex) {
                log.error("Failed while trying to write to file", ex);
            }

        } else {
            log.trace("Open command cancelled by user.");
        }

    }

}

From source file:org.nuclos.client.customcomp.resplan.AbstractResPlanExportDialog.java

@PostConstruct
private void init() {
    double border = 10;
    double inset = 5;
    double size[][] = { { border, 100, inset, 200, inset, 30, inset, 65, border }, // Columns
            { border, 20, inset, 20, inset, 30, border } }; // Rows
    final TableLayout tl = new TableLayout(size);
    setLayout(tl);/*w w  w.  j  a v a  2s  .co  m*/

    final SpringLocaleDelegate sld = getSpringLocaleDelegate();
    final JLabel fileLabel = new JLabel(sld.getText("nuclos.resplan.dialog.file"), SwingConstants.RIGHT);
    add(fileLabel, "1, 1");
    file = new JTextField();
    file.setText(save.getPath());
    add(file, "3, 1");

    final JButton browse = new JButton("...");
    add(browse, "5, 1");

    final JLabel typeLabel = new JLabel(sld.getText("nuclos.resplan.dialog.type"), SwingConstants.RIGHT);
    add(typeLabel, "1, 3");
    fileTypes = new JComboBox(new String[] { ImageType.SVG.getFileExtension(), ImageType.EMF.getFileExtension(),
            ImageType.PNG.getFileExtension() });
    fileTypes.setSelectedItem(defaultFileType);
    fileTypes.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            checkFile();
        }
    });
    add(fileTypes, "3, 3");

    browse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser chooser = new JFileChooser(save.getParent());
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.addChoosableFileFilter(new MyFileFilter((String) fileTypes.getSelectedItem()));
            // chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            final int returnVal = chooser.showSaveDialog(parent);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                save = chooser.getSelectedFile();
                checkFile();
            }
        }
    });

    final JPanel buttons = new JPanel(new FlowLayout());
    add(buttons, "1, 5, 7, 5");

    final JButton export = new JButton(sld.getText("nuclos.resplan.dialog.export"));
    buttons.add(export);
    export.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final String filePath = file.getText();
            if (!filePath.equals(save.getPath())) {
                save = new File(filePath);
            }
            checkFile();
            if (save.exists()) {
                String file = save.getAbsolutePath();
                if (save.canWrite()) {
                    int ans = JOptionPane.showConfirmDialog(AbstractResPlanExportDialog.this,
                            sld.getMessage("general.overwrite.file", "general.overwrite.file", file),
                            sld.getMessage("general.overwrite.file.title", "general.overwrite.file.title"),
                            JOptionPane.OK_CANCEL_OPTION);
                    if (ans != JOptionPane.YES_OPTION) {
                        return;
                    }
                } else {
                    JOptionPane.showMessageDialog(AbstractResPlanExportDialog.this,
                            sld.getMessage("general.notwritable.file", "general.notwritable.file", file),
                            sld.getMessage("general.notwritable.file.title", "general.notwritable.file.title"),
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            export();
            storePreferences();
            dispose();
        }
    });

    final JButton cancel = new JButton(sld.getText("general.cancel"));
    buttons.add(cancel);
    cancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    });

    pack();
    setLocationRelativeTo(parent);
    setVisible(true);
}

From source file:org.nuclos.client.dbtransfer.DBTransferImport.java

private PanelWizardStep newStep5(final MainFrameTab ifrm) {
    final SpringLocaleDelegate localeDelegate = getSpringLocaleDelegate();
    final JLabel lbResult = new JLabel();
    final JEditorPane editLog = new JEditorPane();
    final JScrollPane scrollLog = new JScrollPane(editLog);
    final JLabel lbStructureChangeResult = new JLabel(
            localeDelegate.getMessage("dbtransfer.import.step5.1", "\u00c4nderungen am Datenbankschema"));
    final JButton btnSaveStructureChangeScript = new JButton(
            localeDelegate.getMessage("dbtransfer.import.step5.2", "Script speichern") + "...");
    final JButton btnSaveStructureChangeLog = new JButton(
            localeDelegate.getMessage("dbtransfer.import.step5.3", "Log speichern") + "...");

    editLog.setContentType("text/html");
    editLog.setEditable(false);/* w ww .java  2 s  .  c  om*/

    final PanelWizardStep step = new PanelWizardStep(
            localeDelegate.getMessage("dbtransfer.import.step5.4", "Ergebnis"), localeDelegate.getMessage(
                    "dbtransfer.import.step5.5", "Hier wird Ihnen das Ergebnis des Imports angezeigt.")) {

        @Override
        public void prepare() {
            if (!importTransferResult.hasWarnings() && !importTransferResult.hasCriticals()) {
                lbResult.setText(localeDelegate.getMessage("dbtransfer.import.step5.6", "Import erfolgreich!"));
                this.setComplete(true);
            } else {
                lbResult.setText(
                        localeDelegate.getMessage("dbtransfer.import.step5.7", "Ein Problem ist aufgetreten!"));
                blnSaveOfLogRecommend = true;
            }
            StringBuffer sbLog = new StringBuffer();
            sbLog.append("<html><body>");
            if (!importTransferResult.foundReferences.isEmpty()) {
                sbLog.append(localeDelegate.getMessage("dbtransfer.import.step5.8",
                        "Folgende Konfigurationsobjekte sollten entfernt werden, werden aber noch verwendet")
                        + ":<br />");
                for (Pair<String, String> reference : importTransferResult.foundReferences) {
                    sbLog.append(
                            "- " + reference.y + " ("
                                    + localeDelegate.getLabelFromMetaDataVO(
                                            MetaDataClientProvider.getInstance().getEntity(reference.x))
                                    + ")<br />");
                }
                sbLog.append("<br />" + localeDelegate.getMessage("dbtransfer.import.step5.9",
                        "Passen Sie Ihre Konfiguration dahingehend an oder bearbeiten Sie die Daten,\nwelche noch auf die Konfigurationsobjekte verweisen."));
                sbLog.append("<br />");
            }
            sbLog.append("<font color=\"#800000\">" + importTransferObject.result.getCriticals() + "</font>"
                    + (importTransferObject.result.hasCriticals() ? "<br />" : ""));
            sbLog.append(importTransferResult.getWarnings());
            sbLog.append("</body></html>");
            editLog.setText(sbLog.toString());
        }
    };

    utils.initJPanel(step, new double[] { TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED,
            TableLayout.FILL }, new double[] { 20, TableLayout.FILL, TableLayout.PREFERRED });

    step.add(lbResult, "0,0,3,0");
    step.add(scrollLog, "0,1,3,1");
    step.add(lbStructureChangeResult, "0,2");
    step.add(btnSaveStructureChangeScript, "1,2");
    step.add(btnSaveStructureChangeLog, "2,2");

    btnSaveStructureChangeScript.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                UIUtils.showWaitCursorForFrame(ifrm, true);

                final StringBuffer sbSql = new StringBuffer();
                org.apache.commons.collections.CollectionUtils.forAllDo(importTransferResult.script,
                        new Closure() {
                            @Override
                            public void execute(Object element) {
                                sbSql.append("<DDL>" + element + "</DDL>\n\n");
                            }
                        });

                final JFileChooser filechooser = utils.getFileChooser(
                        localeDelegate.getMessage("configuration.transfer.file.sql", "SQL-Dateien"),
                        ".import-sql.txt");
                filechooser.setSelectedFile(new File(tfTransferFile.getText() + ".import-sql.txt"));
                final int iBtn = filechooser.showSaveDialog(step);

                if (iBtn == JFileChooser.APPROVE_OPTION) {
                    final File file = filechooser.getSelectedFile();
                    if (file != null) {
                        String fileName = file.getPath();

                        if (!fileName.toLowerCase().endsWith(".import-sql.txt")) {
                            fileName += ".import-sql.txt";
                        }

                        File outFile = new File(fileName);
                        final Writer out = new BufferedWriter(new FileWriter(outFile));
                        try {
                            out.write(sbSql.toString());
                        } finally {
                            out.close();
                        }
                        if (blnSaveOfScriptRecommend) {
                            step.setComplete(true);
                        }
                    }
                }
            } catch (Exception e) {
                Errors.getInstance().showExceptionDialog(ifrm, e);
            } finally {
                UIUtils.showWaitCursorForFrame(ifrm, false);
            }
        }
    });
    btnSaveStructureChangeLog.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                UIUtils.showWaitCursorForFrame(ifrm, true);

                final JFileChooser filechooser = utils.getFileChooser(
                        localeDelegate.getMessage("configuration.transfer.file.log", "Log-Dateien"),
                        ".import-log.html");
                filechooser.setSelectedFile(new File(tfTransferFile.getText() + ".import-log.html"));
                final int iBtn = filechooser.showSaveDialog(step);

                if (iBtn == JFileChooser.APPROVE_OPTION) {
                    final File file = filechooser.getSelectedFile();
                    if (file != null) {
                        String fileName = file.getPath();

                        if (!fileName.toLowerCase().endsWith(".import-log.html")) {
                            fileName += ".import-log.html";
                        }

                        File outFile = new File(fileName);
                        final Writer out = new BufferedWriter(new FileWriter(outFile));
                        try {
                            out.write(editLog.getText());
                        } finally {
                            out.close();
                        }
                        if (blnSaveOfLogRecommend) {
                            step.setComplete(true);
                        }
                    }
                }
            } catch (Exception e) {
                Errors.getInstance().showExceptionDialog(ifrm, e);
            } finally {
                UIUtils.showWaitCursorForFrame(ifrm, false);
            }
        }
    });

    return step;
}