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.smart.migrate.ui.MigrateMain.java

private void popExportPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_popExportPlanActionPerformed
    if (listPlan.getSelectedIndex() >= 0) {
        String planName = (String) listPlan.getSelectedValue();
        String planPath = MigratePlanIO.getPlanRoot() + "/" + planName;
        MigratePlan plan = null;//from ww w  .  j a v  a  2 s  .c  om
        try {
            plan = MigratePlanIO.deSerialize(planName);
        } catch (IOException ex) {
            Logger.getLogger(MigrateMain.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MigrateMain.class.getName()).log(Level.SEVERE, null, ex);
        }
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
                if (plan != null) {
                    plan.setName(file.getName());
                    MigratePlanIO.serializeToFile(plan, file);
                    //FileUtils.copyFile(new File(planPath),file);
                    JOptionPane.showMessageDialog(rootPane,
                            bundle.getString("MigrateMain.message.export") + file.getAbsolutePath());
                }
            } catch (IOException ex) {
                Logger.getLogger(MigrateMain.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

From source file:org.smart.migrate.ui.MigrateMain.java

private void popImportPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_popImportPlanActionPerformed
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        String planName = FilenameUtils.getBaseName(file.getName());
        String planPath = MigratePlanIO.getPlanRoot() + "/" + planName;
        try {/*  ww w .  ja  v  a  2s  .  c om*/
            FileUtils.copyFile(file, new File(planPath));
            initModel();
            JOptionPane.showMessageDialog(rootPane, bundle.getString("MigrateMain.message.import") + planName);
        } catch (IOException ex) {
            Logger.getLogger(MigrateMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.squidy.designer.Designer.java

/**
 * Initializes menu bar./*from   w  ww.  j  av  a2  s . c  om*/
 */
private void initMenuBar() {

    JMenuBar menuBar = new JMenuBar();

    JMenu workspace = new JMenu("Workspace");
    workspace.add(new AbstractAction("Open from...") {

        /*
         * (non-Javadoc)
         * 
         * @see
         * java.awt.event.ActionListener#actionPerformed(java.awt.event.
         * ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileHidingEnabled(true);
            fileChooser.setFileFilter(new FileFilter() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.swing.filechooser.FileFilter#accept(java.io.File)
                 */
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".sdy");
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see javax.swing.filechooser.FileFilter#getDescription()
                 */
                @Override
                public String getDescription() {
                    return "Squidy Workspace";
                }
            });
            int option = fileChooser.showOpenDialog(Designer.this);

            if (option == JFileChooser.APPROVE_OPTION) {

                // Stop replacing workspace if currently running.
                if (data != null) {
                    data.getWorkspace().stop();
                }

                File workspaceFile = fileChooser.getSelectedFile();

                if (storage instanceof LocalJAXBStorage) {
                    ((LocalJAXBStorage) storage).setWorkspaceFile(workspaceFile);
                    load();
                } else {
                    try {
                        data = ModelViewHandler.getModelViewHandler().load(new FileInputStream(workspaceFile));

                        WorkspaceShape workspace = data.getWorkspaceShape();
                        workspace.setModel(data);
                        workspace.setStorageHandler(Designer.this);
                        workspace.initialize();
                        LayoutConstraint lc = workspace.getLayoutConstraint();
                        workspace.setScale(lc.getScale());
                        workspace.setOffset(lc.getX(), lc.getY());

                        getCanvas().getLayer().addChild(workspace);

                        zoomToZoomedShape(data);
                    } catch (SquidyException e1) {
                        e1.printStackTrace();
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    });

    workspace.add(new AbstractAction("Export as...") {

        /*
         * (non-Javadoc)
         * 
         * @see
         * java.awt.event.ActionListener#actionPerformed(java.awt.event.
         * ActionEvent)
         */
        public void actionPerformed(ActionEvent e) {

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileHidingEnabled(true);
            fileChooser.setFileFilter(new FileFilter() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.swing.filechooser.FileFilter#accept(java.io.File)
                 */
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".sdy");
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see javax.swing.filechooser.FileFilter#getDescription()
                 */
                @Override
                public String getDescription() {
                    return "Squidy Workspace";
                }
            });

            if (storage instanceof LocalJAXBStorage) {
                fileChooser.setSelectedFile(((LocalJAXBStorage) storage).getWorkspaceFile());
            }

            int option = fileChooser.showSaveDialog(Designer.this);

            if (option == JFileChooser.APPROVE_OPTION) {

                File workspaceFile = fileChooser.getSelectedFile();

                try {
                    ModelViewHandler.getModelViewHandler().save(new FileOutputStream(workspaceFile), data);
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });

    JMenu options = new JMenu("Options");
    rendering.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            VisualShape.setRenderPrimitiveRect(rendering.isSelected());
            data.setRenderPrimitiveRect(rendering.isSelected());
            storage.store(data);
            repaint();
        }
    });
    options.add(rendering);

    JMenu storage = new JMenu("Storage");

    ButtonGroup group = new ButtonGroup();

    final JRadioButtonMenuItem storageLocalJAXB = new JRadioButtonMenuItem("Local JAXB");
    storageLocalJAXB.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (storageLocalJAXB.isSelected()) {
                setStorageMode(StorageMode.FILE);
            }
        }
    });
    storage.add(storageLocalJAXB);
    group.add(storageLocalJAXB);

    final JRadioButtonMenuItem storageBaseX = new JRadioButtonMenuItem("BaseX");
    storageBaseX.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (storageBaseX.isSelected()) {
                setStorageMode(StorageMode.BASEX);
            }
        }
    });
    storageBaseX.setSelected(storageType.equals(BaseXStorage.class));

    storage.add(storageBaseX);
    group.add(storageBaseX);
    options.add(storage);

    menuBar.add(workspace);
    menuBar.add(options);

    setJMenuBar(menuBar);
}

From source file:org.squidy.LocalJAXBStorage.java

/**
 * @return/*  ww  w. j ava 2  s.  c  o  m*/
 */
private File getWorkspaceFileOfSaveDialog() {
    storeInProgress = true;
    try {
        JFileChooser fileChooser = new JFileChooser();

        int option = fileChooser.showSaveDialog(Designer.getInstance());

        if (option == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            setWorkspaceFile(file);
            return file;
        }
        return null;
    } finally {
        storeInProgress = false;
    }
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openJFileChooser(int mode, String dialogTitle, boolean open, String filename,
        FileNameExtensionFilter filter) {
    JFileChooser fileChooser;
    // are we forced to open the legacy file chooser?
    if ("true".equals(System.getProperty("tmm.legacy.filechooser"))) {
        fileChooser = new JFileChooser();
    } else {//from  w ww  . j  a v a  2s.com
        fileChooser = new NativeFileChooser();
    }

    fileChooser.setFileSelectionMode(mode);
    if (lastDir != null) {
        fileChooser.setCurrentDirectory(lastDir.toFile());
    }
    fileChooser.setDialogTitle(dialogTitle);

    int result = -1;
    if (open) {
        result = fileChooser.showOpenDialog(MainWindow.getFrame());
    } else {
        if (StringUtils.isNotBlank(filename)) {
            fileChooser.setSelectedFile(new File(filename));
            fileChooser.setFileFilter(filter);
        }
        result = fileChooser.showSaveDialog(MainWindow.getFrame());
    }

    if (result == JFileChooser.APPROVE_OPTION) {
        if (mode == JFileChooser.DIRECTORIES_ONLY) {
            lastDir = fileChooser.getSelectedFile().toPath();
        } else {
            lastDir = fileChooser.getSelectedFile().getParentFile().toPath();
        }
        return fileChooser.getSelectedFile().toPath();
    }

    return null;
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename./*from  w  w  w . j a va2s  .  c  om*/
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.tros.logo.swing.LogoMenuBar.java

/**
 * Set up the export menu.//from   w ww.j  a  va  2s  .c  om
 *
 * @return
 */
private JMenu setupExportMenu() {
    JMenu exportMenu = new JMenu(Localization.getLocalizedString("ExportMenu"));

    JMenuItem exportGif = new JMenuItem(Localization.getLocalizedString("ExportGIF"));
    JMenuItem exportPng = new JMenuItem(Localization.getLocalizedString("ExportPNG"));
    JMenuItem exportSvg = new JMenuItem(Localization.getLocalizedString("ExportSVG"));

    exportSvg.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                if (Drawable.class.isAssignableFrom(canvas.getClass())) {
                    try (FileOutputStream fos = new FileOutputStream(new File(filename))) {
                        generateSVG((Drawable) canvas, fos);
                        fos.flush();
                    } catch (IOException ex) {
                        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class).warn(null,
                                ex);
                    }
                }
            }
        }
    });

    exportGif.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                final String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Drawable.class.isAssignableFrom(canvas.getClass())
                                && BufferedImageProvider.class.isAssignableFrom((canvas.getClass()))) {
                            try {
                                generateGIF(((Drawable) canvas).cloneDrawable(), (BufferedImageProvider) canvas,
                                        filename);
                            } catch (SVGGraphics2DIOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
                t.setDaemon(true);
                t.start();
            }
        }
    });
    exportPng.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                // retrieve image
                if (BufferedImageProvider.class.isAssignableFrom(canvas.getClass())) {
                    generatePNG((BufferedImageProvider) canvas, filename);
                }
            }
        }
    });

    exportMenu.add(exportSvg);
    exportMenu.add(exportGif);
    exportMenu.add(exportPng);
    exportMenu.setMnemonic('X');
    exportSvg.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.ALT_MASK));
    exportGif.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.ALT_MASK));
    exportPng.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_MASK));
    return (exportMenu);
}

From source file:org.tros.torgo.ControllerBase.java

/**
 * Save the script as a new file.// w ww .  j  a va2  s. c om
 */
@Override
public void saveFileAs() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(ControllerBase.class);
    chooser.setCurrentDirectory(
            new File(prefs.get(ControllerBase.class.getName() + "-working-directory", ".")));

    int result = chooser.showSaveDialog(window);

    if (result == JFileChooser.APPROVE_OPTION) {
        filename = chooser.getSelectedFile().getPath();
        prefs.put(ControllerBase.class.getName() + "-working-directory", chooser.getSelectedFile().getParent());
        saveFile();
    }
}

From source file:org.trzcinka.intellitrac.view.toolwindow.tickets.ticket_editor.BaseTicketEditorForm.java

public BaseTicketEditorForm() {
    ticketsModel.getCurrentTicketModel().addListener(this);
    submitChangesButton.addActionListener(retrieveSubmitButtonActionListener());
    changeHistoryButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            TicketChangesHistoryPopup dialog = new TicketChangesHistoryPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getChanges());
            dialog.pack();//w  w  w .  j  a  v  a2s  .  com
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
        }
    });
    downloadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            OutputStream stream = null;
            if (attachment != null) {
                try {
                    byte[] body = gateway.retrieveAttachment(
                            ticketsModel.getCurrentTicketModel().getCurrentTicket().getId(),
                            attachment.getFileName());
                    JFileChooser fc = new JFileChooser();
                    File dir = fc.getCurrentDirectory();
                    fc.setSelectedFile(new File(dir, attachment.getFileName()));
                    int save = fc.showSaveDialog(rootComponent);

                    if (save == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        stream = new FileOutputStream(file);
                        IOUtils.write(body, stream);
                    }
                } catch (ConnectionFailedException e1) {
                    TracGatewayLocator.handleConnectionProblem();
                } catch (IOException e1) {
                    logger.error("Could not save file", e1);
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    });
    showDescriptionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Attachment attachment = (Attachment) attachmentsList.getSelectedValue();
            if (attachment != null) {
                JOptionPane popup = new AttachmentDescriptionPopup(attachment.getDescription());
                JDialog dialog = popup.createDialog(null,
                        MessageFormat.format(
                                bundle.getString("tool_window.tickets.ticket_editor.attachments.popup_title"),
                                attachment.getFileName()));
                dialog.setVisible(true);
                dialog.dispose();
            }
        }
    });
    attachmentsList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            Attachment selected = (Attachment) attachmentsList.getSelectedValue();
            if (selected == null) {
                downloadButton.setEnabled(false);
                showDescriptionButton.setEnabled(false);
            } else {
                downloadButton.setEnabled(true);
                if (!(StringUtils.isEmpty(selected.getDescription()))) {
                    showDescriptionButton.setEnabled(true);
                }
            }
        }
    });
    newAttachmentButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Window window = SwingUtilities.getWindowAncestor(rootComponent);
            NewAttachmentPopup dialog = new NewAttachmentPopup(window,
                    ticketsModel.getCurrentTicketModel().getCurrentTicket().getId());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
            dialog.dispose();
            synchronizeTicket();
        }
    });
    synchronizeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            synchronizeTicket();
        }
    });
}

From source file:org.waterforpeople.mapping.dataexport.KMLApplet.java

private String promptForFile() {
    final JFileChooser fc = new JFileChooser();
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    final String fileName = "GoogleEarth-" + df.format(new Date()) + ".kmz";
    fc.setSelectedFile(new File(fileName));

    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return fc.getSelectedFile().getAbsolutePath();
    } else {/*from   w w  w  .  jav a2s.c  o  m*/
        return null;
    }
}