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:mondrian.gui.Workbench.java

private void saveAsMenuItemActionPerformed(ActionEvent evt) {
    JInternalFrame jf = desktopPane.getSelectedFrame();

    if (jf != null && jf.getContentPane().getComponent(0) instanceof SchemaExplorer) {
        SchemaExplorer se = (SchemaExplorer) jf.getContentPane().getComponent(0);
        java.io.File schemaFile = se.getSchemaFile();
        java.io.File oldSchemaFile = schemaFile;
        java.io.File suggSchemaFile = new File(
                schemaFile == null ? se.getSchema().name.trim() + ".xml" : schemaFile.getName());
        MondrianGuiDef.Schema schema = se.getSchema();
        JFileChooser jfc = new JFileChooser();
        MondrianProperties.instance();/*from  ww w  .  j  a va  2  s .  c  o m*/

        jfc.setSelectedFile(suggSchemaFile);

        if (!isSchemaValid(schema)) {
            // the schema would not be re-loadable.  Abort save.
            return;
        }

        if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                schemaFile = jfc.getSelectedFile();
                if (!oldSchemaFile.equals(schemaFile) && schemaFile.exists()) { // new file already exists, check for overwrite
                    int answer = JOptionPane.showConfirmDialog(null,
                            getResourceConverter().getFormattedString("workbench.saveAs.schema.confirm",
                                    "{0} schema file already exists. Do you want to replace it?",
                                    schemaFile.getAbsolutePath()),
                            getResourceConverter().getString("workbench.saveAs.schema.confirm.title",
                                    "Save As"),
                            JOptionPane.YES_NO_OPTION);
                    if (answer == 1) { //  no=1 ; yes=0
                        return;
                    }
                }

                if (se.isNewFile() && !oldSchemaFile.equals(schemaFile)) {
                    oldSchemaFile.delete();
                }

                if (se.isNewFile()) {
                    se.setNewFile(false);
                }
                se.setDirty(false);
                se.setDirtyFlag(false);

                XMLOutput out = new XMLOutput(new java.io.FileWriter(jfc.getSelectedFile()));
                out.setAlwaysQuoteCData(true);
                out.setIndentString("  ");
                schema.displayXML(out);
                se.setSchemaFile(schemaFile);
                se.setTitle(); // sets title of iframe
                setLastUsed(jfc.getSelectedFile().getName(), jfc.getSelectedFile().toURI().toURL().toString());

                // Update menu item with new file name, then update catalog
                // list for mdx queries
                JMenuItem sMenuItem = schemaWindowMap.get(jf);
                String mtexttokens[] = sMenuItem.getText().split(" ");
                sMenuItem.setText(mtexttokens[0] + " " + se.getSchemaFile().getName());
                // Schema menu item updated, now update mdx query windows
                // with updated catalog list.
                updateMDXCatalogList();
            } catch (Exception ex) {
                LOGGER.error(ex);
            }
        }
    }
}

From source file:com.sshtools.sshterm.SshTerminalPanel.java

public void actionPerformed(ActionEvent event) {
    // Get the name of the action command
    String command = event.getActionCommand();

    if (sessionActions.containsKey(event.getActionCommand())) {
        SessionProviderAction action = (SessionProviderAction) sessionActions.get(event.getActionCommand());
        SessionProviderFrame frame;/*w w  w .java2 s.  c o m*/
        // Do we have an existing frame?
        for (Iterator it = sessionFrames.iterator(); it.hasNext();) {
            frame = (SessionProviderFrame) it.next();
            if (action.getProvider().getProviderClass().isInstance(frame.getSessionPanel())
                    && frame.getSessionPanel().singleFrame()) {
                frame.show();
                return;
            }
        }

        try {
            frame = new SessionProviderFrame(getCurrentConnectionProfile(), ssh, action.getProvider());
            if (frame.initFrame(getApplication())) {
                frame.show();
                sessionFrames.add(frame);
            }

        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    /*if ((shiftAction != null)
        && command.equals(shiftAction.getActionCommand())) {
      //boolean error = false;
        try {
          SessionProviderFrame browserFrame = new SessionProviderFrame(
         getCurrentConnectionProfile(),
                                ssh,
         SessionProviderFactory.getInstance().getProvider("shift"));
          if (PreferencesStore.preferenceExists(PREF_SHIFT_GEOMETRY)) {
    browserFrame.setBounds(PreferencesStore.getRectangle(
        PREF_SHIFT_GEOMETRY, browserFrame.getBounds()));
          }
          else {
    browserFrame.setLocation(40, 40);
          }
          browserFrame.init(getApplication());
          browserFrame.show();
          browserFrames.add(browserFrame);
        }
        catch (Exception e) {
          showExceptionMessage("Error", e.getMessage());
        }
      }
      /*if (browserFrame != null) {
         //  We need to go back to windowed mode if in full screen mode
         if (!browserFrame.isVisible()) {
           setFullScreenMode(false);
         }
         browserFrame.setVisible(!browserFrame.isVisible());
       }*/

    /* if ( (tunnelingAction != null)
         && command.equals(tunnelingAction.getActionCommand())) {
         try {
    if(tunnelingFrame==null) {
    tunnelingFrame = new SessionProviderFrame(
         getCurrentConnectionProfile(),
                                  ssh,
         SessionProviderFactory.getInstance().getProvider("tunneling"));
    /*if (PreferencesStore.preferenceExists(PREF_SHIFT_GEOMETRY)) {
       tunnelingFrame.setBounds(PreferencesStore.getRectangle(
           PREF_SHIFT_GEOMETRY, tunnelingFrame.getBounds()));
     }
     else {
       tunnelingFrame.setLocation(40, 40);
     }*/

    /*      }
    tunnelingFrame.init(getApplication());
    tunnelingFrame.show();
        }
        catch (Exception e) {
    showExceptionMessage("Error", e.getMessage());
        }*/

    /*if (portForwardingDialog == null) {
         Window parent = (Window) SwingUtilities.getAncestorOfClass(Window.class,
     this);
       if (parent instanceof JFrame) {
         portForwardingDialog = new JDialog( (JFrame) parent,
                                      "Port Forwarding", false);
       }
       else if (parent instanceof JDialog) {
         portForwardingDialog = new JDialog( (JDialog) parent,
                                      "Port Forwarding", false);
       }
       else {
         portForwardingDialog = new JDialog( (JFrame)null,
                                      "Port Forwarding", false);
       }
       portForwardingDialog.getContentPane().setLayout(new BorderLayout());
       portForwardingDialog.getContentPane().add(portForwardingPane,
                                           BorderLayout.CENTER);
       portForwardingDialog.pack();
       if (PreferencesStore.preferenceExists(
     PREF_PORT_FORWARDING_GEOMETRY)) {
         portForwardingDialog.setBounds(PreferencesStore
                                  .getRectangle(
       PREF_PORT_FORWARDING_GEOMETRY,
       portForwardingDialog.getBounds()));
       }
       else {
         portForwardingDialog.setLocation(40, 40);
         portForwardingDialog.setSize(new Dimension(260, 420));
       }
       PreferencesStore.restoreTableMetrics(portForwardingPane
                                      .getPortForwardingTable(),
     PREF_PORT_FORWARDING_FORWARDS_TABLE_METRICS,
     new int[] {68, 62, 44, 54, 98, 78});
       PreferencesStore.restoreTableMetrics(portForwardingPane.
                                      getActiveChannelPane()
                                      .getActiveChannelTable(),
     PREF_PORT_FORWARDING_ACTIVE_TABLE_METRICS,
     new int[] {22, 22, 92, 264});
       if (PreferencesStore.preferenceExists(
     PREF_PORT_FORWARDING_DIVIDER_LOCATION)) {
         portForwardingPane.setDividerLocation(PreferencesStore
                                         .getInt(
       PREF_PORT_FORWARDING_DIVIDER_LOCATION, 100));
       }
       else {
         portForwardingPane.setDividerLocation(0.75d);
       }
     }
     //  We need to go back to windowed mode if in full screen mode
     if (!portForwardingDialog.isVisible()) {
       setFullScreenMode(false);
     }
     portForwardingDialog.setVisible(!portForwardingDialog.isVisible());*/
    //}

    if ((stopAction != null) && command.equals(stopAction.getActionCommand())) {
        stopRecording();
    }

    if ((recordAction != null) && command.equals(recordAction.getActionCommand())) {
        //  We need to go back to windowed mode if in full screen mode
        setFullScreenMode(false);

        // Select the file to record to
        JFileChooser fileDialog = new JFileChooser(System.getProperty("user.home"));
        int ret = fileDialog.showSaveDialog(this);

        if (ret == fileDialog.APPROVE_OPTION) {
            recordingFile = fileDialog.getSelectedFile();

            if (recordingFile.exists()
                    && (JOptionPane.showConfirmDialog(this, "File exists. Are you sure?", "File exists",
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)) {
                return;
            }

            try {
                recordingOutputStream = new FileOutputStream(recordingFile);
                statusBar.setStatusText("Recording to " + recordingFile.getName());
                setAvailableActions();
            } catch (IOException ioe) {
                showExceptionMessage("Error", "Could not open file for recording\n\n" + ioe.getMessage());
            }
        }
    }

    if ((playAction != null) && command.equals(playAction.getActionCommand())) {
        //  We need to go back to windowed mode if in full screen mode
        setFullScreenMode(false);

        // Select the file to record to
        JFileChooser fileDialog = new JFileChooser(System.getProperty("user.home"));
        int ret = fileDialog.showOpenDialog(this);

        if (ret == fileDialog.APPROVE_OPTION) {
            File playingFile = fileDialog.getSelectedFile();
            InputStream in = null;

            try {
                statusBar.setStatusText("Playing from " + playingFile.getName());
                in = new FileInputStream(playingFile);

                byte[] b = null;
                int a = 0;

                while (true) {
                    a = in.available();

                    if (a == -1) {
                        break;
                    }

                    if (a == 0) {
                        a = 1;
                    }

                    b = new byte[a];
                    a = in.read(b);

                    if (a == -1) {
                        break;
                    }

                    //emulation.write(b);
                    emulation.getOutputStream().write(b);
                }

                statusBar.setStatusText("Finished playing " + playingFile.getName());
                setAvailableActions();
            } catch (IOException ioe) {
                statusBar.setStatusText("Error playing " + playingFile.getName());
                showExceptionMessage("Error", "Could not open file for playback\n\n" + ioe.getMessage());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ioe) {
                        log.error(ioe);
                    }
                }
            }
        }
    }

    if ((newAction != null) && command.equals(newAction.getActionCommand())) {
        setFullScreenMode(false);

        // Clear the screen
        emulation.clearScreen();
        emulation.setCursorPosition(0, 0);

        // Force a repaint
        terminal.refresh();

        SshToolsConnectionProfile p = SshToolsConnectionPanel.showConnectionDialog(this,
                getCurrentConnectionProfile(), getAdditionalConnectionTabs());

        if (p != null) {
            currentConnectionProfile = p;
            setContainerTitle(null);
            setNeedSave(true);
            connect(p, true);
        } else {
            log.info("New connection cancelled");
        }

        return;
    }

    if ((closeAction != null) && command.equals(closeAction.getActionCommand())) {
        if (ssh != null) {
            if (performVerifiedDisconnect(true)) {
                disconnecting = true;
                ssh.disconnect();
            }
        }
    }

    if ((openAction != null) && command.equals(openAction.getActionCommand())) {
        open();
    }

    if ((saveAction != null) && command.equals(saveAction.getActionCommand())) {
        // Make sure we dont have a null connection object
        saveConnection(false);
    }

    if ((saveAsAction != null) && command.equals(saveAsAction.getActionCommand())) {
        saveConnection(true);
    }

    //  Keygen
    if ((keygenAction != null) && event.getActionCommand().equals(keygenAction.getActionCommand())) {
        if (keygenFrame == null) {
            keygenFrame = new com.sshtools.common.keygen.Main();
            keygenFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            keygenFrame.pack();
            UIUtil.positionComponent(SwingConstants.CENTER, keygenFrame);
        }

        if (!keygenFrame.isVisible()) {
            setFullScreenMode(false);
        }

        keygenFrame.setVisible(!keygenFrame.isVisible());
    }

    //GSI options
    if ((proxyInfoAction != null) && command.equals(proxyInfoAction.getActionCommand())) {
        ProxyHelper.showProxyInfo(getContainer().getWindow());
    }
    if ((proxyDestroyAction != null) && command.equals(proxyDestroyAction.getActionCommand())) {
        ProxyHelper.destroyProxy();
        setAvailableActions();
    }
}

From source file:org.gumtree.vis.hist2d.Hist2DPanel.java

@Override
public void doExport(IExporter exporter) 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);
        }//from w  w  w . j ava 2 s .  c  om
    }
    String fileExtension = exporter.getExtensionName();
    ExtensionFileFilter extensionFilter = new ExtensionFileFilter(exporter.toString(), "." + fileExtension);
    fileChooser.addChoosableFileFilter(extensionFilter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        //           String selectedDescription = fileChooser.getFileFilter().getDescription();
        if (!filename.toLowerCase().endsWith("." + fileExtension)) {
            filename = filename + "." + fileExtension;
        }
        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);
        } else {
            selectedFile.createNewFile();
        }
        if (confirm == JOptionPane.YES_OPTION) {
            exporter.export(selectedFile, getDataset());
            System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL, fileChooser.getSelectedFile().getParent());
        }
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchSelectionFrame.java

private void exportAsHTML() {
    List<Village> selection = getSelectedElements();
    if (selection.isEmpty()) {
        showInfo("Keine Drfer ausgewhlt");
        return;/*from   w w w  . ja  v  a 2s. c o  m*/
    }
    //do HTML export
    String dir = GlobalOptions.getProperty("screen.dir");

    JFileChooser chooser = null;
    try {
        //handle vista problem
        chooser = new JFileChooser(dir);
    } catch (Exception e) {
        JOptionPaneHelper.showErrorBox(this,
                "Konnte Dateiauswahldialog nicht ffnen.\nMglicherweise verwendest du Windows Vista. Ist dies der Fall, beende DS Workbench, klicke mit der rechten Maustaste auf DSWorkbench.exe,\n"
                        + "whle 'Eigenschaften' und deaktiviere dort unter 'Kompatibilitt' den Windows XP Kompatibilittsmodus.",
                "Fehler");
        return;
    }

    chooser.setDialogTitle("Datei auswhlen");
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {

        @Override
        public boolean accept(File f) {
            return (f != null) && (f.isDirectory() || f.getName().endsWith(".html"));
        }

        @Override
        public String getDescription() {
            return "*.html";
        }
    });
    //open dialog
    chooser.setSelectedFile(new File(dir + "/Dorfliste.html"));
    int ret = chooser.showSaveDialog(this);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            //check extension
            File f = chooser.getSelectedFile();
            String file = f.getCanonicalPath();
            if (!file.endsWith(".html")) {
                file += ".html";
            }

            //check overwrite
            File target = new File(file);
            if (target.exists()) {
                if (JOptionPaneHelper.showQuestionConfirmBox(this, "Bestehende Datei berschreiben?",
                        "berschreiben", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                    //do not overwrite
                    return;
                }
            }
            //do export
            SelectionHTMLExporter.doExport(target, selection);
            GlobalOptions.addProperty("screen.dir", target.getParent());
            showSuccess("Auswahl erfolgreich gespeichert");
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Willst du die erstellte Datei jetzt im Browser betrachten?", "Information", "Nein",
                    "Ja") == JOptionPane.YES_OPTION) {
                BrowserInterface.openPage(target.toURI().toURL().toString());
            }
        } catch (Exception inner) {
            logger.error("Failed to write selection to HTML", inner);
            showError("Fehler beim Speichern");
        }
    }
}

From source file:musite.ui.MusiteResultPanel.java

private void exportComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportComboBoxActionPerformed
    String name = panelName.replaceAll("[\\\\/:\\*\\?\"<>\\|]+", "-");
    String defaultFile = MusiteInit.defaultPath + File.separator + name;
    if (sliderTitleComboBox.getSelectedItem().equals(SPECIFICITY)) {
        defaultFile += String.format("-Sp_%.2f", specificity);
    } else {/*from   ww w .j ava 2s  .  c  o  m*/
        defaultFile += String.format("-Score_%.3f", threshold);
    }
    defaultFile += ".result";

    switch (exportComboBox.getSelectedIndex()) {
    case 1: // tab-delimited text file
    {
        JFileChooser fc = new JFileChooser(MusiteInit.defaultPath);
        fc.setSelectedFile(new File(defaultFile));

        ArrayList<String> exts = new ArrayList<String>(1);
        String fasta = "txt";
        exts.add(fasta);
        FileExtensionsFilter fastaFilter = new FileExtensionsFilter(exts, "Tab-delimited file (.txt)");
        fc.addChoosableFileFilter(fastaFilter);

        //fc.setAcceptAllFileFilterUsed(true);
        fc.setDialogTitle("Save the the result to...");
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            MusiteInit.defaultPath = file.getParent();

            String filePath = MusiteInit.defaultPath + File.separator + file.getName();

            String ext = FilePathParser.getExt(filePath);
            if (ext == null || !ext.equalsIgnoreCase("txt")) {
                filePath += ".txt";
            }

            if (IOUtil.fileExist(filePath)) {
                int ret = JOptionPane.showConfirmDialog(this, "Are you sure to replace the existing file?",
                        "Relace the existing file?", JOptionPane.YES_NO_OPTION);
                if (ret == JOptionPane.NO_OPTION)
                    break;
            }

            Vector<Vector> data = formatData(proteinList, false, true);
            int n = data.size();
            ArrayList<String> dataOut = new ArrayList(n + 1);
            dataOut.add(StringUtils.join(header.iterator(), '\t'));

            for (Vector vec : data) {
                dataOut.add(StringUtils.join(vec.iterator(), '\t'));
            }

            try {
                IOUtil.writeCollectionAscii(dataOut, filePath);
            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "Error: failed to write the file.");
                break;
            }

            JOptionPane.showMessageDialog(this, "Successfully exported.");
        }

        break;
    }
    //            case 2: // fasta
    //            {
    //                JFileChooser fc = new JFileChooser(MusiteInit.defaultPath);
    //                fc.setSelectedFile(new File(defaultFile));
    //
    //                ArrayList<String> exts = new ArrayList<String>(1);
    //                String fasta = "fasta";
    //                exts.add(fasta);
    //                FileExtensionsFilter fastaFilter = new FileExtensionsFilter(exts,"Fasta file (.fasta)");
    //                fc.addChoosableFileFilter(fastaFilter);
    //
    //                //fc.setAcceptAllFileFilterUsed(true);
    //                fc.setDialogTitle("Save the the result to...");
    //                int returnVal = fc.showSaveDialog(this);
    //                if (returnVal == JFileChooser.APPROVE_OPTION) {
    //                    File file = fc.getSelectedFile();
    //                    MusiteInit.defaultPath = file.getParent();
    //
    //                    String filePath = MusiteInit.defaultPath + File.separator + file.getName();
    //
    //                    String ext = FilePathParser.getExt(filePath);
    //                    if (ext==null||!ext.equalsIgnoreCase("fasta")) {
    //                        filePath += ".fasta";
    //                    }
    //
    //                    if (IOUtil.fileExist(filePath)) {
    //                        int ret = JOptionPane.showConfirmDialog(this, "Are you sure to replace the existing file?", "Relace the existing file?", JOptionPane.YES_NO_OPTION);
    //                        if (ret==JOptionPane.NO_OPTION)
    //                            break;
    //                    }
    //
    //                    ProteinsWriter writer = new ModifiedProteinsFastaWriter();
    //                    WriteTask writeTask = new WriteTask(resultDisplay, writer, filePath);
    //                    TaskUtil.execute(writeTask);
    //                    if (!writeTask.success()) {
    //                        JOptionPane.showMessageDialog(this, "Failed to export.");
    //                        break;
    //                    }
    //
    //                    JOptionPane.showMessageDialog(this, "Successfully exported.");
    //                }
    //
    //                break;
    //            }
    //            case 3: // xml
    //            {
    //                JFileChooser fc = new JFileChooser(MusiteInit.defaultPath);
    //                fc.setSelectedFile(new File(defaultFile));
    //
    //                ArrayList<String> exts = new ArrayList<String>(1);
    //                String xml = "xml";
    //                exts.add(xml);
    //                FileExtensionsFilter xmlFilter = new FileExtensionsFilter(exts,"XML file (.xml)");
    //                fc.addChoosableFileFilter(xmlFilter);
    //
    //                //fc.setAcceptAllFileFilterUsed(true);
    //                fc.setDialogTitle("Save the the result to...");
    //                int returnVal = fc.showSaveDialog(this);
    //                if (returnVal == JFileChooser.APPROVE_OPTION) {
    //                    File file = fc.getSelectedFile();
    //                    MusiteInit.defaultPath = file.getParent();
    //
    //                    String filePath = MusiteInit.defaultPath + File.separator + file.getName();
    //
    //                    String ext = FilePathParser.getExt(filePath);
    //                    if (ext==null||!ext.equalsIgnoreCase("xml")) {
    //                        filePath += ".xml";
    //                    }
    //
    //                    if (IOUtil.fileExist(filePath)) {
    //                        int ret = JOptionPane.showConfirmDialog(this, "Are you sure to replace the existing file?", "Relace the existing file?", JOptionPane.YES_NO_OPTION);
    //                        if (ret==JOptionPane.NO_OPTION)
    //                            break;
    //                    }
    //
    //                    ProteinsXMLWriter writer = ProteinsXMLWriter.createWriter();
    //                    WriteTask xmlWriteTask = new WriteTask(resultDisplay, writer, filePath);
    //                    TaskUtil.execute(xmlWriteTask);
    //                    if (!xmlWriteTask.success()) {
    //                        JOptionPane.showMessageDialog(this, "Failed to export.");
    //                        break;
    //                    }
    //
    //                    JOptionPane.showMessageDialog(this, "Successfully exported.");
    //                }
    //
    //                break;
    //            }
    }
    exportComboBox.setSelectedIndex(0);
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void fireSaveScreenshotEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireSaveScreenshotEvent
    String dir = GlobalOptions.getProperty("screen.dir");

    JFileChooser chooser = null;
    try {//from  w  w w  .  j a  v a2 s.  c o m
        chooser = new JFileChooser(dir);
    } catch (Exception e) {
        JOptionPaneHelper.showErrorBox(this,
                "Konnte Dateiauswahldialog nicht ffnen.\nMglicherweise verwendest du Windows Vista. Ist dies der Fall, beende DS Workbench, klicke mit der rechten Maustaste auf DSWorkbench.exe,\n"
                        + "whle 'Eigenschaften' und deaktiviere dort unter 'Kompatibilitt' den Windows XP Kompatibilittsmodus.",
                "Fehler");
        return;
    }
    chooser.setDialogTitle("Speichern unter...");
    chooser.setSelectedFile(new File("map"));

    final String type = (String) jFileTypeChooser.getSelectedItem();
    chooser.setFileFilter(new FileFilter() {

        @Override
        public boolean accept(File f) {
            return (f != null) && (f.isDirectory() || f.getName().endsWith(type));
        }

        @Override
        public String getDescription() {
            return "*." + type;
        }
    });

    int ret = chooser.showSaveDialog(jScreenshotControl);

    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            File f = chooser.getSelectedFile();
            String file = f.getCanonicalPath();
            if (!file.endsWith(type)) {
                file += "." + type;
            }
            File target = new File(file);
            if (target.exists()) {
                //ask if overwrite
                if (JOptionPaneHelper.showQuestionConfirmBox(jScreenshotControl,
                        "Existierende Datei berschreiben?", "berschreiben", "Nein",
                        "Ja") != JOptionPane.YES_OPTION) {
                    return;
                }
            }
            ImageIO.write(mScreenshotPanel.getResult(jTransparancySlider.getValue()), type, target);
            GlobalOptions.addProperty("screen.dir", target.getParent());

        } catch (Exception e) {
            logger.error("Failed to write map shot", e);
        }
    }
}

From source file:ded.ui.DiagramController.java

/** Prompt user for file name and save to it. */
public void chooseAndSaveToFile() {
    // Prompt for a file name, confirming if the file already exists.
    String result = this.fileName;
    while (true) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(this.currentFileChooserDirectory);
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Diagram Editor Files (.ded)", "ded"));
        int res = chooser.showSaveDialog(this);
        if (res != JFileChooser.APPROVE_OPTION) {
            return;
        }/*from ww w . j a va 2 s  .  c  o  m*/
        this.currentFileChooserDirectory = chooser.getCurrentDirectory();
        result = chooser.getSelectedFile().getAbsolutePath();

        if (new File(result).exists()) {
            res = JOptionPane.showConfirmDialog(this,
                    "A file called \"" + result + "\" already exists.  Overwrite it?", "Confirm Overwrite",
                    JOptionPane.YES_NO_OPTION);
            if (res != JOptionPane.YES_OPTION) {
                continue; // Ask again.
            }
        }

        break;
    }

    // Save to the chosen file.
    this.saveToNamedFile(result);
}

From source file:domain.Excel.java

private boolean showOpenFileDialog() {

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Specify a file to save");
        FileFilter filter1 = new ExtensionFileFilter("XLS", "XLS");

        fileChooser.setFileFilter(filter1);

        int userSelection = fileChooser.showSaveDialog(parent);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            XLSFile = fileToSave.getAbsolutePath() + ".xls";
            System.out.println("Save as file: " + fileToSave.getAbsolutePath());
            return true;
        }//from   w w  w  . ja  va 2 s.c o  m
        return false;
    }

From source file:musite.ui.MusiteResultPanel.java

public boolean saveResult(boolean showConfirm) {
    JFileChooser fc = new JFileChooser(MusiteInit.defaultPath);

    // TODO: windows reserverd
    String fileName = panelName.replaceAll("[" + StringUtil.toOct("|\\?*<\":>+[]/") + "]+", "_");
    fc.setSelectedFile(new File(MusiteInit.defaultPath + File.separator + fileName + ".pred.xml.gz"));

    ArrayList<String> exts = new ArrayList<String>(2);
    exts.add("xml");
    exts.add("xml.gz");
    fc.addChoosableFileFilter(new FileExtensionsFilter(exts, "Prediction XML file (.xml, .xml.gz)"));

    exts = new ArrayList<String>(2);
    exts.add("pred.xml");
    exts.add("pred.xml.gz");
    fc.addChoosableFileFilter(new FileExtensionsFilter(exts, "Prediction result file (pred.xml, pred.xml.gz)"));

    //fc.setAcceptAllFileFilterUsed(true);
    fc.setDialogTitle("Save the the result to...");
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        MusiteInit.defaultPath = file.getParent();

        String filePath = MusiteInit.defaultPath + File.separator + file.getName();

        //            if (!filePath.toLowerCase().endsWith(".xml")&&!filePath.toLowerCase().endsWith(".xml.gz")) {
        //                filePath += ".pred.xml.gz";
        //            }

        if (IOUtil.fileExist(filePath)) {
            int ret = JOptionPane.showConfirmDialog(this, "Are you sure to replace the existing file?",
                    "Relace the existing file?", JOptionPane.YES_NO_OPTION);
            if (ret == JOptionPane.NO_OPTION)
                return false;
        }// www  .  j  a v  a  2s.c  om

        PredictionResultXMLWriter writer = PredictionResultXMLWriter.createWriter();
        WriteTask task = new WriteTask(result, writer, filePath);

        TaskUtil.execute(task);
        if (task.success()) {
            if (showConfirm)
                JOptionPane.showMessageDialog(this, "Result saved!");
            saved = true;
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "Failed to save the result.");
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.gumtree.vis.plot1d.Plot1DPanel.java

@Override
public void doExport(IExporter exporter) throws IOException {
    boolean isMultipleSeries = getDataset().getSeriesCount() > 1;
    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);
        }/*from  w  w w.j av a  2  s .c o  m*/
    }
    String fileExtension = exporter.getExtensionName();
    ExtensionFileFilter extensionFilter = new ExtensionFileFilter(exporter.toString(), "." + fileExtension);
    fileChooser.addChoosableFileFilter(extensionFilter);
    if (isMultipleSeries) {
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }
    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        int confirm = JOptionPane.YES_OPTION;
        File selectedFile;
        if (isMultipleSeries) {
            selectedFile = new File(filename);
            if (!selectedFile.exists()) {
                selectedFile.mkdirs();
            }
            exporter.export(selectedFile, getDataset());
            System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL,
                    fileChooser.getSelectedFile().getAbsolutePath());
        } else {
            if (!filename.toLowerCase().endsWith("." + fileExtension)) {
                filename = filename + "." + fileExtension;
            }
            selectedFile = new File(filename);
            if (selectedFile.exists()) {
                confirm = JOptionPane.showConfirmDialog(this, selectedFile.getName() + " exists, overwrite?",
                        "Confirm Overwriting", JOptionPane.YES_NO_OPTION);
            } else {
                selectedFile.createNewFile();
            }
            if (confirm == JOptionPane.YES_OPTION) {
                exporter.export(selectedFile, getDataset());
                System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL,
                        fileChooser.getSelectedFile().getParent());
            }
        }
    }
}