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:com.ev.export.AnnualPDFExporter.java

@Override
public String chooseFile() throws IOException {
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    jfc.showSaveDialog(MainFrame.getInstance());
    File selectedFile = jfc.getSelectedFile();
    if (selectedFile == null) {
        throw new IOException("No file chosen.");
    }/*from   w  ww . j a  v a  2s .  c om*/
    return selectedFile.getCanonicalPath() + File.separator + year + PDF_SUFFIX;
}

From source file:SaveImage.java

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    if (cb.getActionCommand().equals("SetFilter")) {
        setOpIndex(cb.getSelectedIndex());
        repaint();//w  w w  .j  a  va  2s  .  c  o  m
    } else if (cb.getActionCommand().equals("Formats")) {
        /*
         * Save the filtered image in the selected format. The selected item will
         * be the name of the format to use
         */
        String format = (String) cb.getSelectedItem();
        /*
         * Use the format name to initialise the file suffix. Format names
         * typically correspond to suffixes
         */
        File saveFile = new File("savedimage." + format);
        JFileChooser chooser = new JFileChooser();
        chooser.setSelectedFile(saveFile);
        int rval = chooser.showSaveDialog(cb);
        if (rval == JFileChooser.APPROVE_OPTION) {
            saveFile = chooser.getSelectedFile();
            /*
             * Write the filtered image in the selected format, to the file chosen
             * by the user.
             */
            try {
                ImageIO.write(biFiltered, format, saveFile);
            } catch (IOException ex) {
            }
        }
    }
}

From source file:de.erdesignerng.visual.editor.openxavaexport.OpenXavaExportEditor.java

private void commandChooseSrcDirectory() {
    JFileChooser theChooser = new JFileChooser();
    theChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (theChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File theBaseDirectory = theChooser.getSelectedFile();
        editingView.getSrcDirectory().setText(theBaseDirectory.toString());
    }/*  ww w .  ja  v  a2  s  .co  m*/
}

From source file:org.cytoscape.dyn.internal.graphMetrics.GraphMetricsResultsPanel.java

/**
 * /*from w  w w .  j  a  va2  s  .  c  om*/
 */
public void saveData() {
    JFileChooser saveFileDialog = new JFileChooser();
    int save = saveFileDialog.showSaveDialog(null);
    if (save == JFileChooser.APPROVE_OPTION) {
        FileWriter writer = null;
        try {
            File file = saveFileDialog.getSelectedFile();
            if (file.exists()) {
                if (JOptionPane.showConfirmDialog(null,
                        "The specified file already exists. Do you want to overwrite it?",
                        "Warning - File Exists", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                    writer = new FileWriter(file);
                    for (int i = 0; i < this.dataset.getSeriesCount(); i++) {
                        writer.write(this.dataset.getSeries(i).getKey().toString() + "\n");
                        for (int j = 0; j < this.dataset.getSeries(i).getItemCount(); j++) {
                            writer.write(this.dataset.getSeries(i).getDataItem(j).toString() + "\n");
                        }
                    }
                }
            } else {
                writer = new FileWriter(file);
                for (int i = 0; i < this.dataset.getSeriesCount(); i++) {
                    writer.write(this.dataset.getSeries(i).getKey().toString() + "\n");
                    for (int j = 0; j < this.dataset.getSeries(i).getItemCount(); j++) {
                        writer.write(this.dataset.getSeries(i).getDataItem(j).toString() + "\n");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:it.unibas.spicygui.controllo.mapping.ActionExecuteXQuery.java

private File generateFile() {
    JFileChooser chooser = vista.getFileChooserSalvaXmlXsd();
    boolean continua = true;
    File file;/*  w  ww . j  a  v  a2 s.c om*/
    while (continua) {
        int returnVal = chooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
            if (!file.exists() || chiediConferma()) {
                return file;
            }
        } else {
            continua = false;
        }
    }
    return null;
}

From source file:com.floreantpos.bo.actions.DataExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    Session session = null;/*www. j a v  a  2 s.  com*/
    Transaction transaction = null;
    FileWriter fileWriter = null;
    GenericDAO dao = new GenericDAO();

    try {
        JFileChooser fileChooser = getFileChooser();
        int option = fileChooser.showSaveDialog(com.floreantpos.util.POSUtil.getBackOfficeWindow());
        if (option != JFileChooser.APPROVE_OPTION) {
            return;
        }

        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            option = JOptionPane.showConfirmDialog(com.floreantpos.util.POSUtil.getFocusedWindow(),
                    Messages.getString("DataExportAction.1") + file.getName() + "?", //$NON-NLS-1$//$NON-NLS-2$
                    Messages.getString("DataExportAction.3"), //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION);
            if (option != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // fixMenuItemModifierGroups();

        JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();

        session = dao.createNewSession();
        transaction = session.beginTransaction();

        Elements elements = new Elements();

        //          * 2. USERS
        //          * 3. TAX
        //          * 4. MENU_CATEGORY
        //          * 5. MENU_GROUP
        //          * 6. MENU_MODIFIER
        //          * 7. MENU_MODIFIER_GROUP
        //          * 8. MENU_ITEM
        //          * 9. MENU_ITEM_SHIFT
        //          * 10. RESTAURANT
        //          * 11. USER_TYPE
        //          * 12. USER_PERMISSION
        //          * 13. SHIFT

        elements.setTaxes(TaxDAO.getInstance().findAll(session));
        elements.setMenuCategories(MenuCategoryDAO.getInstance().findAll(session));
        elements.setMenuGroups(MenuGroupDAO.getInstance().findAll(session));
        elements.setMenuModifiers(MenuModifierDAO.getInstance().findAll(session));
        elements.setMenuModifierGroups(MenuModifierGroupDAO.getInstance().findAll(session));
        elements.setMenuItems(MenuItemDAO.getInstance().findAll(session));
        elements.setMenuItemModifierGroups(MenuItemModifierGroupDAO.getInstance().findAll(session));

        //           elements.setUsers(UserDAO.getInstance().findAll(session));
        //           
        //           elements.setMenuItemShifts(MenuItemShiftDAO.getInstance().findAll(session));
        //           elements.setRestaurants(RestaurantDAO.getInstance().findAll(session));
        //           elements.setUserTypes(UserTypeDAO.getInstance().findAll(session));
        //           elements.setUserPermissions(UserPermissionDAO.getInstance().findAll(session));
        //           elements.setShifts(ShiftDAO.getInstance().findAll(session));

        m.marshal(elements, writer);

        transaction.commit();

        fileWriter = new FileWriter(file);
        fileWriter.write(writer.toString());
        fileWriter.close();

        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(),
                Messages.getString("DataExportAction.4")); //$NON-NLS-1$

    } catch (Exception e1) {
        transaction.rollback();
        PosLog.error(getClass(), e1);
        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(), e1.getMessage());
    } finally {
        IOUtils.closeQuietly(fileWriter);
        dao.closeSession(session);
    }
}

From source file:it.unibas.spicygui.controllo.file.ActionSaveAsMappingTask.java

@Override
public void performAction() {
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    JFileChooser chooser = vista.getFileChooserSalvaXmlXsd();
    continua = true;//from  w ww.j av  a 2 s .co  m
    File file;
    while (continua) {
        int returnVal = chooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                file = chooser.getSelectedFile();
                if (!file.exists()) {
                    daoMappingTask.saveMappingTask(mappingTask, file.getAbsolutePath());
                    mappingTask.setModified(false);
                    mappingTask.setToBeSaved(false);
                    continua = false;
                    esito = true;
                } else {
                    chiediConferma(file, mappingTask);
                }
            } catch (DAOException ex) {
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.SAVE_ERROR) + " : " + ex.getMessage(),
                        DialogDescriptor.ERROR_MESSAGE));
                logger.error(ex);
                continua = false;
                esito = false;
            }
        } else {
            continua = false;
            esito = false;
        }
    }
}

From source file:MainWindow.java

public MainWindow() {
    // Login Routine
    loginDialog = new LoginDialog();
    // loginDialog.nameField.setText("cornelius.preidel@googlemail.com");
    // loginDialog.passwordField.setText("germany");
    loginDialog.setSize(400, 150);//from   w w  w .ja va  2 s. c  o  m
    loginDialog.setModal(true);
    loginDialog.setLocationRelativeTo(null);
    loginDialog.setVisible(true);

    // Get the connected ApiCore
    core = loginDialog._core;

    // Init the UI
    mainFrame = new JFrame("MainApplication");
    mainFrame.setSize(500, 500);
    mainFrame.setLocationRelativeTo(null);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setLayout(new GridLayout(5, 1));

    // WebProjectsList webprojectlist = new WebProjectsList(core);
    // mainFrame.add(webprojectlist);

    // Create the APIS
    Teams teamsAPI = new Teams(core);
    final Projects projectsAPI = new Projects(core);
    final Divisions divisionsAPI = new Divisions(core);
    final Attachments attachmentAPI = new Attachments(core);
    final Issues issueAPI = new Issues(core);

    // TEAMS List
    TeamsList teamList = new TeamsList();
    teamList.setTeams(teamsAPI.GetTeams());
    mainFrame.add(teamList);

    // PROJECTS  List
    projectsList = new ProjectsList();
    mainFrame.add(projectsList);

    // DIVISIONS List
    divisionsList = new DivisionsList();
    // mainFrame.add(divisionsList);

    // DIVISIONS Table
    divisionsTable = new DivisionsTable(core);
    mainFrame.add(divisionsTable);

    // Attachments
    attachmentsList = new AttachmentsList();
    mainFrame.add(attachmentsList);

    // Attachments
    issuesList = new IssuesList();
    mainFrame.add(issuesList);

    PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
            String property = propertyChangeEvent.getPropertyName();
            if ("selectedTeam".equals(property)) {
                DtoTeam selectedTeam = (DtoTeam) propertyChangeEvent.getNewValue();

                // Set the global slug
                core.currentTeam = selectedTeam;
                projectsList.setProjects(projectsAPI.GetProjects());
            } else if ("selectedProject".equals(property)) {
                DtoProject selectedProject = (DtoProject) propertyChangeEvent.getNewValue();
                // Divisions
                divisionsList.setDivisions(divisionsAPI.GetDivisions(selectedProject.GetId()));
                divisionsTable.setDivisions(divisionsAPI.GetDivisions(selectedProject.GetId()));
                // Attachments
                attachmentsList.setAttachments(attachmentAPI.GetAttachments(selectedProject.GetId()));
                // Issues
                issuesList.setIssues(issueAPI.GetIssues(selectedProject.GetId()));
            } else if ("selectedDivision".equals(property)) {
                DtoDivision selectedDivision = (DtoDivision) propertyChangeEvent.getNewValue();
                // What to do with the division?
            } else if ("selectedIssue".equals(property)) {
                DtoIssue selectedDivision = (DtoIssue) propertyChangeEvent.getNewValue();
                // What to do with the division?
            } else {
                if ("selectedAttachment".equals(property)) {
                    DtoAttachment selectedAttachment = (DtoAttachment) propertyChangeEvent.getNewValue();
                    InputStream stream = attachmentAPI.DownloadAttachment(selectedAttachment.GetId());

                    try {
                        byte[] bytes = IOUtils.toByteArray(stream);
                        JFileChooser chooser = new JFileChooser();
                        int returnVal = chooser.showSaveDialog(chooser);
                        File file = chooser.getSelectedFile();

                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(bytes);
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        LOG.error(e.getMessage(), e);
                    }
                }
            }
        }
    };

    // Add Listener
    teamList.addPropertyChangeListener(propertyChangeListener);
    projectsList.addPropertyChangeListener(propertyChangeListener);
    divisionsList.addPropertyChangeListener(propertyChangeListener);
    divisionsTable.addPropertyChangeListener(propertyChangeListener);
    attachmentsList.addPropertyChangeListener(propertyChangeListener);
    issuesList.addPropertyChangeListener(propertyChangeListener);
}

From source file:uk.co.petertribble.jkstat.gui.KstatBaseChartFrame.java

/**
 * Saves the current chart as an image in png format. The user can select
 * the filename, and is asked to confirm the overwrite of an existing file.
 *///from w ww . j  av a  2s.  c om
public void saveImage() {
    JFileChooser fc = new JFileChooser();
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        if (f.exists()) {
            int ok = JOptionPane.showConfirmDialog(this,
                    KstatResources.getString("SAVEAS.OVERWRITE.TEXT") + " " + f.toString(),
                    KstatResources.getString("SAVEAS.CONFIRM.TEXT"), JOptionPane.YES_NO_OPTION);
            if (ok != JOptionPane.YES_OPTION) {
                return;
            }
        }
        BufferedImage bi = kbc.getChart().createBufferedImage(500, 300);
        try {
            ImageIO.write(bi, "png", f);
            /*
             * According to the API docs this should throw an IOException
             * on error, but this doesn't seem to be the case. As a result
             * it's necessary to catch exceptions more generally. Even this
             * doesn't work properly, but at least we manage to convey the
             * message to the user that the write failed, even if the
             * error itself isn't handled.
             */
        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(this, ioe.toString(), KstatResources.getString("SAVEAS.ERROR.TEXT"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.pgptool.gui.ui.tools.browsefs.SaveFileChooserDialog.java

public String askUserForFile() {
    JFileChooser ofd = prepareFileChooser();

    boolean userWantsToSelectOtherFile = true;
    File retFile = null;/*from  ww w  . j  ava 2s . c  om*/
    while (userWantsToSelectOtherFile) {
        int result = ofd.showSaveDialog(parentWindow);
        if (result != JFileChooser.APPROVE_OPTION) {
            return onDialogClosed(null, ofd);
        }
        retFile = ofd.getSelectedFile();
        if (retFile == null) {
            return onDialogClosed(null, ofd);
        }

        File retFileWithExt = new File(enforceExtension(retFile.getAbsolutePath(), ofd));
        if (userWantsToSelectOtherFile = retFileWithExt.exists()) {
            if (UiUtils.confirm("confirm.overWriteExistingFile",
                    new Object[] { retFileWithExt.getAbsolutePath() }, parentWindow)) {
                userWantsToSelectOtherFile = false;
            }
        }
    }

    Preconditions.checkState(retFile != null, "Useless check but it makes Eclipse NPE checker happier");
    String ret = retFile.getAbsolutePath();
    ret = onDialogClosed(ret, ofd);
    return ret;
}