Example usage for javax.swing JFileChooser setSelectedFile

List of usage examples for javax.swing JFileChooser setSelectedFile

Introduction

In this page you can find the example usage for javax.swing JFileChooser setSelectedFile.

Prototype

@BeanProperty(preferred = true)
public void setSelectedFile(File file) 

Source Link

Document

Sets the selected file.

Usage

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

/**
 * Opens file browser panel and asks user to select a filename/directory.
 *
 * @param parentpanel//from  w w w.  j  a va  2  s  .c  om
 *            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: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);
        }/*from w w w  . j a va2  s .  c  o  m*/
    });
    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;
}

From source file:org.colombbus.tangara.net.FileReceptionDialog.java

private void setTargetFile() {
    File targetDir = Configuration.instance().getUserHome();
    JFileChooser chooserDlg = new JFileChooser(targetDir);

    String filterMsg = Messages.getString("FileReceptionDialog.filter.allFiles");
    SimpleFileFilter filter = new SimpleFileFilter(filterMsg);
    chooserDlg.setFileFilter(filter);/*  w  ww  . j av  a 2  s  .  c  o  m*/

    File originalSelFile = new File(targetDir, sourceFilename);
    File curSelFile = originalSelFile;
    boolean showDialog = true;
    while (showDialog) {
        chooserDlg.setSelectedFile(curSelFile);
        int userAction = chooserDlg.showSaveDialog(owner);
        curSelFile = chooserDlg.getSelectedFile();
        switch (userAction) {
        case JFileChooser.CANCEL_OPTION:
            showDialog = false;
            break;
        case JFileChooser.APPROVE_OPTION:
            if (curSelFile.exists()) {
                String title = Messages.getString("FileReceptionDialog.overwrite.title");
                String msgPattern = Messages.getString("FileReceptionDialog.overwrite.message");
                String overwriteMsg = MessageFormat.format(msgPattern, curSelFile.getName());
                Object[] options = { Messages.getString("FileReceptionDialog.yes"),
                        Messages.getString("FileReceptionDialog.no") };
                int userChoice = JOptionPane.showOptionDialog(owner, overwriteMsg, title,
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a
                        // custom Icon
                        options, // the titles of buttons
                        options[0]);
                if (userChoice == JOptionPane.OK_OPTION) {
                    if (saveFileAs(curSelFile)) {
                        showDialog = false;
                    }
                }
            } else if (saveFileAs(curSelFile)) {
                showDialog = false;
            }
            break;
        case JFileChooser.ERROR_OPTION:
            LOG.error("Error in file chooser dialog");
            // TODO what to do in case of error ? Retry ?
            showDialog = false;
            break;
        }
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.s3.Cockpit.java

/**
 * Downloads the objects currently selected in the objects table. The user is
 * prompted//from   w  w  w.  ja  va 2s. c  o  m
 * Prepares to perform a download of objects from S3 by prompting the user for a directory
 * to store the files in, then performing the download.
 *
 * @throws IOException
 */
private void downloadSelectedObjects() {
    // Prompt user to choose directory location for downloaded files (or cancel download altogether)
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose directory to save S3 files in");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setSelectedFile(downloadDirectory);

    int returnVal = fileChooser.showDialog(ownerFrame, "Choose Directory");
    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;
    }

    downloadDirectory = fileChooser.getSelectedFile();

    // Find clashing files
    final Map filesAlreadyInDownloadDirectoryMap = new HashMap();
    S3Object[] objectsForDownload = getSelectedObjects();
    for (int i = 0; i < objectsForDownload.length; i++) {
        File file = new File(downloadDirectory, objectsForDownload[i].getKey());
        if (file.exists()) {
            filesAlreadyInDownloadDirectoryMap.put(objectsForDownload[i].getKey(), file);
        }
    }

    // Build map of S3 Objects being downloaded.
    final Map s3DownloadObjectsMap = FileComparer.getInstance().populateS3ObjectMap("", objectsForDownload);

    final HyperlinkActivatedListener hyperlinkListener = this;

    runInBackgroundThread(new Runnable() {
        public void run() {
            // Retrieve details of objects for download
            if (!retrieveObjectsDetails(getSelectedObjects())) {
                return;
            }

            try {
                final FileComparerResults comparisonResults = compareRemoteAndLocalFiles(
                        filesAlreadyInDownloadDirectoryMap, s3DownloadObjectsMap);

                DownloadPackage[] downloadPackages = buildDownloadPackageList(comparisonResults,
                        s3DownloadObjectsMap);
                if (downloadPackages == null) {
                    return;
                }

                s3ServiceMulti.downloadObjects(currentSelectedBucket, downloadPackages);

            } catch (final Exception e) {
                runInDispatcherThreadImmediately(new Runnable() {
                    public void run() {
                        String message = "Unable to download objects";
                        log.error(message, e);
                        ErrorDialog.showDialog(ownerFrame, hyperlinkListener, message, e);
                    }
                });
            }
        }
    });
}

From source file:org.freeplane.features.url.mindmapmode.ExportBranchAction.java

public void actionPerformed(final ActionEvent e) {
    final NodeModel existingNode = Controller.getCurrentModeController().getMapController().getSelectedNode();
    final Controller controller = Controller.getCurrentController();
    final MapModel parentMap = controller.getMap();
    if (parentMap == null || existingNode == null || existingNode.isRoot()) {
        controller.getViewController().err("Could not export branch.");
        return;//  w ww. j  a v a  2  s.c  o m
    }
    if (parentMap.getFile() == null) {
        controller.getViewController().out("You must save the current map first!");
        ((MModeController) Controller.getCurrentModeController()).save();
    }
    JFileChooser chooser;
    final File file = parentMap.getFile();
    if (file == null) {
        return;
    }
    chooser = new JFileChooser(file.getParentFile());
    chooser.setSelectedFile(
            new File(createFileName(TextController.getController().getShortText(existingNode))));
    if (((MFileManager) UrlManager.getController()).getFileFilter() != null) {
        chooser.addChoosableFileFilter(((MFileManager) UrlManager.getController()).getFileFilter());
    }
    final int returnVal = chooser.showSaveDialog(controller.getViewController().getContentPane());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        final String ext = FileUtils.getExtension(chosenFile.getName());
        if (!ext.equals(org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION_WITHOUT_DOT)) {
            chosenFile = new File(chosenFile.getParent(),
                    chosenFile.getName() + org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION);
        }
        try {
            Compat.fileToUrl(chosenFile);
        } catch (final MalformedURLException ex) {
            UITools.errorMessage(TextUtils.getText("invalid_url"));
            return;
        }
        if (chosenFile.exists()) {
            final int overwriteMap = JOptionPane.showConfirmDialog(
                    controller.getMapViewManager().getMapViewComponent(),
                    TextUtils.getText("map_already_exists"), "Freeplane", JOptionPane.YES_NO_OPTION);
            if (overwriteMap != JOptionPane.YES_OPTION) {
                return;
            }
        }
        /*
         * Now make a copy from the node, remove the node from the map and
         * create a new Map with the node as root, store the new Map, add
         * the copy of the node to the parent, and set a link from the copy
         * to the new Map.
         */
        final NodeModel parent = existingNode.getParentNode();
        final File oldFile = parentMap.getFile();

        final URI newUri = LinkController.toLinkTypeDependantURI(oldFile, chosenFile);
        final URI oldUri = LinkController.toLinkTypeDependantURI(chosenFile, file);
        ((MLinkController) LinkController.getController()).setLink(existingNode, oldUri,
                LinkController.LINK_ABSOLUTE);
        final int nodePosition = parent.getChildPosition(existingNode);
        final ModeController modeController = Controller.getCurrentModeController();
        modeController.undoableResolveParentExtensions(LogicalStyleKeys.NODE_STYLE, existingNode);
        final MMapController mMapController = (MMapController) modeController.getMapController();
        mMapController.deleteNode(existingNode);
        {
            final IActor actor = new IActor() {
                private final boolean wasFolded = existingNode.isFolded();

                public void undo() {
                    PersistentNodeHook.removeMapExtensions(existingNode);
                    existingNode.setMap(parentMap);
                    existingNode.setFolded(wasFolded);
                }

                public String getDescription() {
                    return "ExportBranchAction";
                }

                public void act() {
                    existingNode.setParent(null);
                    existingNode.setFolded(false);
                    mMapController.newModel(existingNode);
                }
            };
            Controller.getCurrentModeController().execute(actor, parentMap);
        }
        final MapModel map = existingNode.getMap();
        IExtension[] oldExtensions = map.getRootNode().getSharedExtensions().values()
                .toArray(new IExtension[] {});
        for (final IExtension extension : oldExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.removeExtension(clazz);
            }
        }
        final Collection<IExtension> newExtensions = parentMap.getRootNode().getSharedExtensions().values();
        for (final IExtension extension : newExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.addExtension(extension);
            }
        }
        ((MFileManager) UrlManager.getController()).save(map, chosenFile);
        final NodeModel newNode = mMapController.addNewNode(parent, nodePosition, existingNode.isLeft());
        ((MTextController) TextController.getController()).setNodeText(newNode, existingNode.getText());
        modeController.undoableCopyExtensions(LogicalStyleKeys.NODE_STYLE, existingNode, newNode);
        map.getFile();
        ((MLinkController) LinkController.getController()).setLink(newNode, newUri,
                LinkController.LINK_ABSOLUTE);
        map.destroy();
    }
}

From source file:org.giswater.controller.MenuController.java

private String chooseFileSetup(String fileName) {

    String path = "";
    JFileChooser chooser = new JFileChooser();
    FileFilter filter = new FileNameExtensionFilter("EXE extension file", "exe");
    chooser.setFileFilter(filter);/*from www.j  a  v a  2s. c  om*/
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle(Utils.getBundleString("file_exe"));
    File file = new File(usersFolder + fileName);
    chooser.setCurrentDirectory(file);
    chooser.setSelectedFile(file);
    int returnVal = chooser.showOpenDialog(mainFrame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File fileSql = chooser.getSelectedFile();
        path = fileSql.getAbsolutePath();
        if (path.lastIndexOf(".") == -1) {
            path += ".exe";
            fileSql = new File(path);
        }
    }
    return path;

}

From source file:org.jab.docsearch.DocSearch.java

private void doSave() {
    setStatus(I18n.getString("tooltip.save"));

    // defaultSaveFolder
    JFileChooser fds = new JFileChooser();
    fds.setDialogTitle(I18n.getString("windowtitle.save"));

    String saveName;/* www  .j  av  a  2 s .c  o  m*/
    if (curPage.equals("results")) {
        saveName = "results.htm";
    } else if (curPage.equals("home")) {
        saveName = "home.htm";
    } else {
        saveName = Utils.getNameOnly(curPage);
    }
    saveName = FileUtils.addFolder(defaultSaveFolder, saveName);
    fds.setCurrentDirectory(new File(defaultSaveFolder));
    fds.setSelectedFile(new File(saveName));

    int fileGotten = fds.showDialog(this, I18n.getString("button.save"));
    if (fileGotten == JFileChooser.APPROVE_OPTION) {
        File saveFile = fds.getSelectedFile();
        setStatus(I18n.getString("button.save") + saveFile);

        // get document stream and save it
        String saveText = editorPane.getText();
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileWriter(saveFile));
            pw.print(saveText);
        } catch (IOException ioe) {
            logger.fatal("doSave() failed with IOException", ioe);
            showMessage(dsErrSaFi, "\n" + saveFile);
        } finally {
            IOUtils.closeQuietly(pw);
        }
    }
}

From source file:org.javaswift.cloudie.CloudiePanel.java

protected void onDownloadStoredObject() {
    Container container = getSelectedContainer();
    List<StoredObject> obj = getSelectedStoredObjects();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(lastFolder);
    if (obj.size() == 1) {
        chooser.setSelectedFile(new File(obj.get(0).getName()));
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    } else {/*from ww  w .  j  a  va 2 s . c  o  m*/
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }
    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File selected = chooser.getSelectedFile();
        for (StoredObject so : obj) {
            File target = selected;
            if (target.isDirectory()) {
                target = new File(selected, so.getName());
            }
            if (target.exists()) {
                if (confirm("File '" + target.getName() + "' already exists. Overwrite?")) {
                    doSaveStoredObject(target, container, so);
                }
            } else {
                doSaveStoredObject(target, container, so);
            }
        }
        lastFolder = selected.isFile() ? selected.getParentFile() : selected;
    }

}

From source file:org.jets3t.apps.cockpitlite.CockpitLite.java

/**
 * Prepares to perform a download of objects from S3 by prompting the user for a directory
 * to store the files in, then performing the download.
 *
 * @throws IOException/*  ww w.  j a  va 2s  .c  om*/
 */
private void downloadSelectedObjects() throws IOException {
    // Prompt user to choose directory location for downloaded files (or cancel download altogether)
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose directory to save S3 files in");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setSelectedFile(downloadDirectory);

    int returnVal = fileChooser.showDialog(ownerFrame, "Choose Directory");
    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;
    }

    downloadDirectory = fileChooser.getSelectedFile();

    prepareForObjectsDownload();
}

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

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