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:nl.detoren.ijsco.ui.Mainscreen.java

private void addMenubar() {
    // Menu bar met 1 niveau
    Mainscreen ms = this;
    JMenuBar menubar = new JMenuBar();
    JMenu filemenu = new JMenu("Bestand");
    // File menu/*from ww w . ja v a  2s. c om*/
    JMenuItem item;
    /*      item = new JMenuItem("Openen...");
          item.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
            
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent arg0) {
    // Create a file chooser
    final JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
    // In response to a button click:
    int returnVal = fc.showOpenDialog(ms);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
       File file = fc.getSelectedFile();
       logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
       //controller.leesBestand(file.getAbsolutePath());
       ms.repaint();
    }
             }
          });
          filemenu.add(item);
    */
    /*      item = new JMenuItem("Opslaan");
          item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent arg0) {
    //controller.saveState(true, "save");
             }
          });
          filemenu.add(item);
    */
    filemenu.addSeparator();
    item = new JMenuItem("Instellingen...");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            actieInstellingen();
        }
    });
    item.setAccelerator(KeyStroke.getKeyStroke('I', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    filemenu.add(item);
    filemenu.addSeparator();
    item = new JMenuItem("Afsluiten");
    item.setAccelerator(KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            controller.saveState(false, null);
            System.exit(EXIT_ON_CLOSE);
        }
    });
    filemenu.add(item);
    menubar.add(filemenu);

    /**
     *  Toernooi menu 
      */

    JMenu toernooimenu = new JMenu("Toernooi");
    item = new JMenuItem("Toernooiinformatie");
    item.setAccelerator(KeyStroke.getKeyStroke('T', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //actieNieuweSpeler(null, null);
            bewerkToernooi();
            hoofdPanel.repaint();
        }
    });
    toernooimenu.add(item);
    menubar.add(toernooimenu);

    /**
     *  Spelersdatabase menu 
      */

    JMenu spelermenu = new JMenu("Spelersdatabase");

    item = new JMenuItem("OSBO JSON lijst ophalen (Online)");
    item.setAccelerator(KeyStroke.getKeyStroke('J', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //actieNieuweSpeler(null, null);
            leeslijstOnline("www.osbo.nl", "/jeugd/currentratings.json");
            hoofdPanel.repaint();
        }
    });
    spelermenu.add(item);

    item = new JMenuItem("OSBO htmllijst ophalen !verouderd! (Online)");
    item.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //actieNieuweSpeler(null, null);
            leeslijstOnline("www.osbo.nl", "/jeugd/jrating.htm");
            hoofdPanel.repaint();
        }
    });
    spelermenu.add(item);

    item = new JMenuItem("OSBO/IJSCO compatible lijst inlezen (Bestand)");
    item.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            final JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
            // In response to a button click:
            int returnVal = fc.showOpenDialog(ms);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
                leesOSBOlijstBestand(file.getAbsolutePath());
            }
            hoofdPanel.repaint();
        }
    });
    spelermenu.add(item);

    /*      item = new JMenuItem("Groslijst CSV inlezen (Bestand) N/A");
          item.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieNieuweSpeler(null, null);
    // Create a file chooser
    final JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
    // In response to a button click:
    int returnVal = fc.showOpenDialog(ms);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
       File file = fc.getSelectedFile();
       logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
       leesCSV(file.getAbsolutePath());
    }
    hoofdPanel.repaint();
             }
          });
          spelermenu.add(item);
    */
    menubar.add(spelermenu);

    JMenu deelnemersmenu = new JMenu("Deelnemers");

    item = new JMenuItem("Wis Deelnemerslijst");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            wisDeelnemers();
            hoofdPanel.repaint();
        }
    });
    deelnemersmenu.add(item);

    item = new JMenuItem("Importeren Deelnemerslijst");
    item.setAccelerator(KeyStroke.getKeyStroke('I', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            final JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
            // In response to a button click:
            int returnVal = fc.showOpenDialog(ms);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
                leesDeelnemers(file.getAbsolutePath());
            }
            hoofdPanel.repaint();
        }
    });
    deelnemersmenu.add(item);

    item = new JMenuItem("Export Deelnemerslijst (JSON)");
    item.setAccelerator(KeyStroke.getKeyStroke('E', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("JSON", "json");
            fc.setFileFilter(filter);
            fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
            // In response to a button click:
            int returnVal = fc.showSaveDialog(ms);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
                schrijfDeelnemers(file.getAbsolutePath());
            }
            hoofdPanel.repaint();
        }
    });
    deelnemersmenu.add(item);

    menubar.add(deelnemersmenu);

    JMenu uitslagenmenu = new JMenu("Uitslagen");
    Component hs = this;
    item = new JMenuItem("Importeer uitslagenbestand");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            final JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File(System.getProperty("user.dir")));

            // In response to a button click:
            int returnVal = fc.showOpenDialog(hs);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                logger.log(Level.INFO, "Opening: " + file.getAbsolutePath() + ".");
                status.groepenuitslagen = (GroepsUitslagen) new ExcelImport().importeerUitslagen(file);
                OutputUitslagen ou = new OutputUitslagen();
                ou.exportuitslagen(status.groepenuitslagen);
                IJSCOController.t().wisUitslagen();
                ou.exportJSON(status.groepenuitslagen);
                GroepsUitslagen verwerkteUitslag = new Uitslagverwerker()
                        .verwerkUitslag(status.groepenuitslagen);
                logger.log(Level.INFO, verwerkteUitslag.ToString());
                new OutputUitslagen().exporteindresultaten(verwerkteUitslag);
                JOptionPane.showMessageDialog(null, "Uitslagen geimporteerd en bestanden aangemaakt.");
            }
            hoofdPanel.repaint();
        }
    });

    uitslagenmenu.add(item);
    menubar.add(uitslagenmenu);

    JMenu osbomenu = new JMenu("OSBO");

    item = new JMenuItem("Verstuur uitslagen handmatig.");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            SendAttachmentInEmail SAIM = new SendAttachmentInEmail();
            SAIM.sendAttachement("Uitslagen.json");
            hoofdPanel.repaint();
        }
    });

    osbomenu.add(item);
    menubar.add(osbomenu);

    JMenu helpmenu = new JMenu("Help");

    item = new JMenuItem("Verstuur logging");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Create a file chooser
            SendAttachmentInEmail SAIM = new SendAttachmentInEmail();
            SAIM.sendAttachement("IJSCO_UI.log");
            hoofdPanel.repaint();
        }
    });

    helpmenu.add(item);
    item = new JMenuItem("About");
    item.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            AboutDialog ad = new AboutDialog(ms);
            ad.setVisible(true);
            hoofdPanel.repaint();
        }
    });

    helpmenu.add(item);
    menubar.add(helpmenu);

    /*      JMenu indelingMenu = new JMenu("Indeling");
          //item = new JMenuItem("Automatisch aan/uit");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent event) {
    //actieAutomatisch();
             }
          });
            
          indelingMenu.add(item);
          //item = new JMenuItem("Maak wedstrijdgroep");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieMaakWedstrijdgroep();
             }
          });
            
          indelingMenu.add(item);
          //item = new JMenuItem("Maak speelschema");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evetn) {
    //actieMaakSpeelschema();
             }
          });
          indelingMenu.add(item);
          //item = new JMenuItem("Bewerk speelschema");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent event) {
    //updateAutomatisch(false);
    // ResultaatDialoog
    //actieBewerkSchema();
             }
          });
            
          indelingMenu.add(item);
          indelingMenu.addSeparator();
          //item = new JMenuItem("Export");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent event) {
    //actieExport();
             }
          });
          indelingMenu.add(item);
          indelingMenu.addSeparator();
          //item = new JMenuItem("Vul uitslagen in");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieVoerUitslagenIn();
             }
          });
          indelingMenu.add(item);
          //item = new JMenuItem("Externe spelers");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieExterneSpelers();
             }
          });
          indelingMenu.add(item);
          //item = new JMenuItem("Maak nieuwe stand");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieUpdateStand();
             }
          });
          indelingMenu.add(item);
          indelingMenu.addSeparator();
          //item = new JMenuItem("Volgende ronde");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //actieVolgendeRonde();
             }
          });
          indelingMenu.add(item);
          menubar.add(indelingMenu);
    */
    /*      JMenu overigmenu = new JMenu("Overig");
            
          //item = new JMenuItem("Reset punten");
          item = new JMenuItem("N/A");
          item.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
    //controller.resetPunten();
    hoofdPanel.repaint();
             }
          });
            
          overigmenu.add(item);
          menubar.add(overigmenu);
    */
    this.setJMenuBar(menubar);

}

From source file:nl.tudelft.goal.SimpleIDE.SimpleIDE.java

/**
 * Opens file browser panel and asks user to select a filename/directory.
 *
 * @param parentpanel// w w w.  j  a v a2  s .  co  m
 *            the panel to center this file browser panel on.
 * @param openFile
 *            boolean that must be set to true to open a file dialog, and to
 *            false to open a save dialog.
 * @param title
 *            the title for the file browser panel.
 * @param mode
 *            can be set to FILES_ONLY or DIRECTORIES_ONLY or something else
 *            to fix selection.
 * @param ext
 *            the expected extension. If the extension is not starting with
 *            a dot, we insert a dot. Is enforced (if not null) by simply
 *            adding when user enters a filename without any extension, or
 *            by requesting user to change it if it is not right. If
 *            enforceExtension = true, we throw exception when user changes
 *            extension. If false, we allow explicit differnt extension by
 *            user.
 * @param defaultName
 *            File name that will be suggested (if not null) by the dialog.
 *            Should be of the form defaultName###.extension. Note that if
 *            openFile is set to true then an existing label is picked of
 *            that form, and if openFile is set to false then a new name is
 *            picked.
 * @param startdir
 *            is the suggested start location for the browse. If this is set
 *            to null, {@link System#getProperty(String)} is used with
 *            String="user.home".
 * @param enforceExtension
 *            is set to true if extension MUST be used. false if extension
 *            is only suggestion and can be changed. Only applicable if
 *            extension is not null.
 * @return The selected file. Adds default extension if file path does not
 *         have file extension.
 * @throws GOALCommandCancelledException
 *             if user cancels action.
 * @throws GOALUserError
 *             if user makes incorrect selection.
 *
 */
public static File askFile(Component parentpanel, boolean openFile, String title, int mode, String exten,
        String defaultName, String startdir, boolean enforceExtension)
        throws GOALCommandCancelledException, GOALUserError {
    // insert the leading dot if necessary.
    String extension = (exten == null || exten.startsWith(".")) ? exten //$NON-NLS-1$
            : "." + exten; //$NON-NLS-1$
    /**
     * File name to be returned.
     */
    File selectedFile;
    /**
     * Return state of file chooser.
     */
    int returnState;

    if (startdir == null) {
        startdir = System.getProperty("user.home"); //$NON-NLS-1$
    }

    try {
        File dir = new File(startdir);
        String suggestion = null;
        if (defaultName != null) {
            if (openFile) {
                suggestion = findExistingFilename(dir, defaultName, extension);
            } else {
                suggestion = createNewNonExistingFilename(dir, defaultName, extension);
            }
        }
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(dir);
        chooser.setDialogTitle(title);
        chooser.setFileSelectionMode(mode);
        if (suggestion != null) {
            chooser.setSelectedFile(new File(suggestion));
        }

        if (openFile) {
            returnState = chooser.showOpenDialog(parentpanel);
        } else {
            returnState = chooser.showSaveDialog(parentpanel);
        }

        // TODO: handle ALL return state options + exception here
        if (returnState != JFileChooser.APPROVE_OPTION) {
            throw new GOALCommandCancelledException("user cancelled open dialog."); //$NON-NLS-1$
            // FIXME: why not just return null?
            // That's a clean way of saying that the user did not select
            // any file; cancelling is not a program-breaking offence.
            // (and null will be returned when the user disagrees
            // with overwriting an existing file anyway)
        }

        selectedFile = chooser.getSelectedFile();
        if (openFile && !selectedFile.exists()) {
            // file browsers you can select
            // non-existing files!
            throw new FileNotFoundException("File " //$NON-NLS-1$
                    + selectedFile.getCanonicalPath() + " does not exist."); //$NON-NLS-1$
        }
    } catch (FileNotFoundException e) {
        throw new GOALUserError(e.getMessage(), e);
    } catch (IOException e) {
        throw new GOALUserError(e.getMessage(), e);
    } catch (HeadlessException e) {
        throw new GOALUserError(e.getMessage(), e);
    }

    // Check extension.
    String ext = FilenameUtils.getExtension(selectedFile.getName());
    if (extension != null) {
        if (ext.isEmpty()) {
            selectedFile = new File(selectedFile.getAbsolutePath() + extension);
        } else {
            // Check whether extension is OK.
            if (enforceExtension && !("." + ext).equals(extension)) { //$NON-NLS-1$
                throw new GOALUserError("The file must have extension " //$NON-NLS-1$
                        + extension);
            }
        }
    }
    Extension fileExtension = Extension.getFileExtension(selectedFile.getName());
    if (fileExtension == null) {
        throw new GOALUserError("Files with extension " + ext //$NON-NLS-1$
                + " are not recognized by GOAL"); //$NON-NLS-1$
    }

    // Check whether file name already exists.
    if (!openFile && selectedFile != null && selectedFile.exists()) {
        int selection = JOptionPane.showConfirmDialog(parentpanel, "Overwrite existing file?", "Overwrite?", //$NON-NLS-1$ //$NON-NLS-2$
                JOptionPane.YES_NO_OPTION);
        if (selection != JOptionPane.YES_OPTION) {
            throw new GOALCommandCancelledException("User refused overwrite of file " + selectedFile); //$NON-NLS-1$
        }
    }

    return selectedFile;
}

From source file:openlr.mapviewer.coding.ui.SaveConfigButtonListener.java

@Override
public void actionPerformed(final ActionEvent e) {

    JFileChooser chooser = fileChooserFactory.createFileChooser(FILE_CHOOSER_TOPIC_DECODER_PROPERTIES);
    String codingTypeString = codeOptionsDialog.getCodingType().name().toLowerCase();
    chooser.setDialogTitle("Select the file to save the " + codingTypeString + " properties to");

    int re = chooser.showSaveDialog(codeOptionsDialog);
    if (re == JFileChooser.APPROVE_OPTION) {

        File file = chooser.getSelectedFile();

        if (writePermitted(file)) {

            applyChangesActionListener.applyChanges();

            FileConfiguration currentConfig = codingPropertiesHolder
                    .getProperties(codeOptionsDialog.getCodingType());

            try {

                currentConfig.save(file);

            } catch (ConfigurationException e1) {
                JOptionPane.showMessageDialog(null,
                        "Could not write the properties to file " + file.getAbsolutePath() + ". " + e1,
                        "Write error", JOptionPane.ERROR_MESSAGE);
            }//w ww  .j  a v a 2s . c  om
        }

    }
}

From source file:openqcm.mainGUI.java

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

    // if the button is pressed
    if (saveFileBtn.isSelected() == true) {
        saveFileBtn.setText("Stop Save");
        // open a file chooser
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt", "dat");
        chooser.setFileFilter(filter);//from   ww w .  j  ava 2  s.  c o  m
        int option = chooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            sf = chooser.getSelectedFile();
            saveFileBtn.setText("Stop Save");
            titleJTextField.setText(sf.getName() + " - QCM Data Chart");
            //saveFile = true;
            //jFormattedTextField3.setText(sf.getName());

        } else {
            JOptionPane.showMessageDialog(null, "No file selected", "Error", JOptionPane.ERROR_MESSAGE);
            saveFileBtn.setText("Save File");
            saveFileBtn.setSelected(false);
            titleJTextField.setText("QCM Data Chart");
        }
    } // if the button is released
    else if (saveFileBtn.isSelected() == false) {
        saveFileBtn.setText("Save File");
        titleJTextField.setText("QCM Data Chart");
    }

}

From source file:org.andrewberman.sync.PDFDownloader.java

static File chooseDirectory() throws Exception {
    JFileChooser fc = new JFileChooser();
    // fc.setDialogTitle("Choose Output Directory");

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Choose only directories only.
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    // Open chooser dialog
    int result = fc.showSaveDialog(new JFrame());

    if (result == JFileChooser.CANCEL_OPTION) {
        out.println("Directory choice was canceled. Exiting...");
        // System.exit(1);
        throw new Exception();
    }/*from   w ww.ja  v a2 s .  co  m*/
    File f = fc.getSelectedFile();
    out.println("Chosen directory:" + f);
    return f;
}

From source file:org.apache.cayenne.modeler.dialog.db.merge.MergerOptions.java

/**
 * Allows user to save generated SQL in a file.
 *///from   w w w. ja  va  2s.c om
public void storeSQLAction() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogType(JFileChooser.SAVE_DIALOG);
    fc.setDialogTitle("Save SQL Script");

    Resource projectDir = getApplication().getProject().getConfigurationResource();

    if (projectDir != null) {
        fc.setCurrentDirectory(new File(projectDir.getURL().getPath()));
    }

    if (fc.showSaveDialog(getView()) == JFileChooser.APPROVE_OPTION) {
        refreshGeneratorAction();

        try {
            File file = fc.getSelectedFile();
            FileWriter fw = new FileWriter(file);
            PrintWriter pw = new PrintWriter(fw);
            pw.print(textForSQL);
            pw.flush();
            pw.close();
        } catch (IOException ex) {
            reportError("Error Saving SQL", ex);
        }
    }
}

From source file:org.apache.cayenne.modeler.graph.action.SaveAsImageAction.java

@Override
public void performAction(ActionEvent e) {
    // find start directory in preferences
    FSPath lastDir = getApplication().getFrameController().getLastDirectory();

    // configure dialog
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    lastDir.updateChooser(chooser);/*from  w w w . java2  s .c  o m*/

    chooser.setAcceptAllFileFilterUsed(false);

    String ext = "png";
    chooser.addChoosableFileFilter(FileFilters.getExtensionFileFilter(ext, "PNG Images"));

    int status = chooser.showSaveDialog(Application.getFrame());
    if (status == JFileChooser.APPROVE_OPTION) {
        lastDir.updateFromChooser(chooser);

        String path = chooser.getSelectedFile().getPath();
        if (!path.endsWith("." + ext)) {
            path += "." + ext;
        }

        try {

            JGraph graph = dataDomainGraphTab.getGraph();
            BufferedImage img = graph.getImage(null, 0);

            try (OutputStream out = new FileOutputStream(path);) {
                ImageIO.write(img, ext, out);
                out.flush();
            }

        } catch (IOException ex) {
            logObj.error("Could not save image", ex);
            JOptionPane.showMessageDialog(Application.getFrame(), "Could not save image.", "Error saving image",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.bimserver.client.Client.java

void checkout(SRevision revision) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("IFC File", "ifc"));
    int showSaveDialog = chooser.showSaveDialog(this);
    if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        FileOutputStream fileOutputStream;
        try {//from  w  w w .  j av a  2  s  .  co  m
            fileOutputStream = new FileOutputStream(selectedFile);
            checkout(revision, fileOutputStream, true);
        } catch (FileNotFoundException e) {
            LOGGER.error("", e);
        }
    }
}

From source file:org.bimserver.client.Client.java

public void download(SRevision revision) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("IFC File", "ifc"));
    int showSaveDialog = chooser.showSaveDialog(this);
    if (showSaveDialog == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        try {/*  w w w.j  av  a  2 s.  com*/
            FileOutputStream fileOutputStream = new FileOutputStream(selectedFile);
            download(revision.getOid(), fileOutputStream, true);
        } catch (FileNotFoundException e) {
            LOGGER.error("", e);
        }
    }
}

From source file:org.broad.igv.hic.MainWindow.java

private JMenuBar createMenuBar(final JPanel hiCPanel) {

    JMenuBar menuBar = new JMenuBar();

    //======== fileMenu ========
    JMenu fileMenu = new JMenu("File");

    //---- loadMenuItem ----
    JMenuItem loadMenuItem = new JMenuItem();
    loadMenuItem.setText("Load...");
    loadMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadMenuItemActionPerformed(e);
        }/* w  w  w.j  a  v  a  2  s  .  com*/
    });
    fileMenu.add(loadMenuItem);

    //---- loadFromURL ----
    JMenuItem loadFromURL = new JMenuItem();
    JMenuItem getEigenvector = new JMenuItem();
    final JCheckBoxMenuItem viewDNAseI;

    loadFromURL.setText("Load from URL ...");
    loadFromURL.setName("loadFromURL");
    loadFromURL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadFromURLActionPerformed(e);
        }
    });
    fileMenu.add(loadFromURL);
    fileMenu.addSeparator();

    // Pre-defined datasets.  TODO -- generate from a file
    addPredefinedLoadItems(fileMenu);

    JMenuItem saveToImage = new JMenuItem();
    saveToImage.setText("Save to image");
    saveToImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BufferedImage image = (BufferedImage) createImage(1000, 1000);
            Graphics g = image.createGraphics();
            hiCPanel.paint(g);

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File("image.png"));
            int actionDialog = fc.showSaveDialog(null);
            if (actionDialog == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists()) {
                    actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
                    if (actionDialog == JOptionPane.NO_OPTION || actionDialog == JOptionPane.CANCEL_OPTION)
                        return;
                }
                try {
                    // default if they give no format or invalid format
                    String fmt = "jpg";
                    int ind = file.getName().indexOf(".");
                    if (ind != -1) {
                        String ext = file.getName().substring(ind + 1);
                        String[] strs = ImageIO.getWriterFormatNames();
                        for (String aStr : strs)
                            if (ext.equals(aStr))
                                fmt = ext;
                    }
                    ImageIO.write(image.getSubimage(0, 0, 600, 600), fmt, file);
                } catch (IOException ie) {
                    System.err.println("Unable to write " + file + ": " + ie);
                }
            }
        }
    });
    fileMenu.add(saveToImage);
    getEigenvector = new JMenuItem("Get principal eigenvector");
    getEigenvector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getEigenvectorActionPerformed(e);
        }
    });
    fileMenu.add(getEigenvector);
    //---- exit ----
    JMenuItem exit = new JMenuItem();
    exit.setText("Exit");
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            exitActionPerformed(e);
        }
    });
    fileMenu.add(exit);

    menuBar.add(fileMenu);

    //======== Tracks menu ========

    JMenu tracksMenu = new JMenu("Tracks");

    viewEigenvector = new JCheckBoxMenuItem("View Eigenvector...");
    viewEigenvector.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewEigenvector.isSelected()) {
                if (eigenvectorTrack == null) {
                    eigenvectorTrack = new EigenvectorTrack("eigen", "Eigenvectors");
                }
                updateEigenvectorTrack();
            } else {
                trackPanel.setEigenvectorTrack(null);
                if (HiCTrackManager.getLoadedTracks().isEmpty()) {
                    trackPanel.setVisible(false);
                }
            }
        }
    });
    viewEigenvector.setEnabled(false);
    tracksMenu.add(viewEigenvector);

    JMenuItem loadItem = new JMenuItem("Load...");
    loadItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadHostedTrack(MainWindow.this);
        }

    });
    tracksMenu.add(loadItem);

    JMenuItem loadFromFileItem = new JMenuItem("Load from file...");
    loadFromFileItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadTrackFromFile(MainWindow.this);
        }

    });
    tracksMenu.add(loadFromFileItem);

    menuBar.add(tracksMenu);

    //======== Extras menu ========
    JMenu extrasMenu = new JMenu("Extras");

    JMenuItem dumpPearsons = new JMenuItem("Dump pearsons matrix ...");
    dumpPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            BasicMatrix pearsons = hic.zd.getPearsons();
            try {
                String chr1 = hic.getChromosomes()[hic.zd.getChr1()].getName();
                String chr2 = hic.getChromosomes()[hic.zd.getChr2()].getName();
                int binSize = hic.zd.getBinSize();
                File initFile = new File("pearsons_" + chr1 + "_" + "_" + chr2 + "_" + binSize + ".bin");
                File f = FileDialogUtils.chooseFile("Save pearsons", null, initFile, FileDialogUtils.SAVE);
                if (f != null) {
                    ScratchPad.dumpPearsonsBinary(pearsons, chr1, chr2, hic.zd.getBinSize(), f);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });

    JMenuItem dumpEigenvector = new JMenuItem("Dump eigenvector ...");
    dumpEigenvector.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                ScratchPad.dumpEigenvector(hic);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(dumpEigenvector);

    JMenuItem readPearsons = new JMenuItem("Read pearsons...");
    readPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                File f = FileDialogUtils.chooseFile("Pearsons file (Yunfan format)");
                if (f != null) {
                    BasicMatrix bm = ScratchPad.readPearsons(f.getAbsolutePath());

                    hic.zd.setPearsons(bm);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(readPearsons);

    extrasMenu.add(dumpPearsons);
    menuBar.add(extrasMenu);

    return menuBar;
}