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:com.nbt.TreeFrame.java

protected JFileChooser createFileChooser() {
    JFileChooser fc = new JFileChooser();
    fc.setFileHidingEnabled(false);/*from w ww . j a v a2  s . co  m*/
    fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    String description = "named binary tag";
    FileFilter filter = new FileNameExtensionFilter(description, "mcr", "dat", "dat_old");
    fc.setFileFilter(filter);
    Preferences prefs = getPreferences();
    String exportFile = prefs.get(KEY_FILE, null);
    if (exportFile == null) {
        File cwd = new File(".");
        fc.setCurrentDirectory(cwd);
    } else {
        File selectedFile = new File(exportFile);
        fc.setSelectedFile(selectedFile);
    }
    return fc;
}

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

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

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

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

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

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

    int ret = chooser.showSaveDialog(jScreenshotControl);

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

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

From source file:com.freedomotic.jfrontend.MainWindow.java

/**
 * /*from   ww w.  j  av a 2 s. c o  m*/
 * @param evt 
 */
private void mnuNewEnvironmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewEnvironmentActionPerformed
    // we are about to make changes to environments: we'd better save current status
    mnuSaveActionPerformed(null);
    File oldEnv = api.environments().findAll().get(0).getSource();

    //creates a new environment coping it from a template
    File template = new File(
            Info.PATHS.PATH_DATA_FOLDER + "/furn/templates/template-square/template-square.xenv");

    LOG.info("Opening new environment template file \"{}\"", template.getAbsolutePath());
    setEnvironment(api.environments().findAll().get(0));

    try {

        EnvironmentLogic enL = api.environments().loadEnvironmentFromFile(template);

        if (enL != null) {
            //EnvObjectPersistence.loadObjects(EnvironmentPersistence.getEnvironments().get(0).getObjectFolder(), false);
            final JFileChooser fc = new JFileChooser(oldEnv.getParentFile().getParentFile());
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.setDialogTitle(api.getI18n().msg("select_env_folder_save"));
            fc.setSelectedFile(oldEnv.getParentFile());
            int returnVal = fc.showSaveDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File folder = fc.getSelectedFile();

                if (!folder.getName().isEmpty()) {
                    if (!folder.getAbsolutePath().equalsIgnoreCase(oldEnv.getParentFile().getAbsolutePath())) {
                        // we are making a new environment set
                        api.environments().deleteAll();
                    }
                    EnvironmentLogic newenv = api.environments().copy(enL);
                    newenv.setSource(new File(folder + "/" + newenv.getPojo().getUUID() + ".xenv"));
                    setEnvironment(newenv);
                    api.environments().saveAs(newenv, folder);
                }
            } else {
                LOG.info("Save command cancelled by user.");
                //reload the old file
                api.environments().init(oldEnv.getParentFile());
                setEnvironment(api.environments().findAll().get(0));
            }
        }
    } catch (Exception e) {
        LOG.error(Freedomotic.getStackTraceInfo(e));
    }

    setWindowedMode();
}

From source file:lu.fisch.moenagade.model.Project.java

public void openImage(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedImage));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override//from  w  w  w.  ja  v a 2s.c  o  m
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported image files (*.jpg, *.png)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add image");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadImage(fc.getSelectedFile());
    }

}

From source file:lu.fisch.moenagade.model.Project.java

public void openSound(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedSound));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override/*from ww w  .ja  va2s  . c om*/
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("wav")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported sound files (*.wav)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add sound");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadSound(fc.getSelectedFile());
    }

}

From source file:com.opendoorlogistics.studio.scripts.editor.ScriptEditor.java

protected SimpleAction createSaveScriptAsAction() {
    return new SimpleAction("Save as", "Save script as", "document-save-as-2-16x16.png") {

        @Override/* w  w w .  j  a v a 2s . c o  m*/
        public void actionPerformed(ActionEvent e) {
            validateScriptData();

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new FileNameExtensionFilter(
                    AppConstants.ORG_NAME + " script  (" + ScriptConstants.FILE_EXT.toLowerCase() + ")",
                    ScriptConstants.FILE_EXT));
            File file = ScriptEditor.this.file;
            if (file == null) {
                file = createDefaultFilename();
            }

            if (file == null) {
                file = PreferencesManager.getSingleton().getScriptsDirectory();
            }

            // ensure absolute
            if (file != null) {
                file = file.getAbsoluteFile();
            }

            // ensure have filename
            if (file != null && file.isDirectory()) {
                file = new File(file, createDefaultPathlessFilename());
            }

            if (file != null) {
                chooser.setCurrentDirectory(file.getParentFile());
                chooser.setSelectedFile(file);
            }

            if (chooser.showSaveDialog(ScriptEditor.this) == JFileChooser.APPROVE_OPTION) {
                save(chooser.getSelectedFile());
            }
        }
    };
}

From source file:mondrian.gui.Workbench.java

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

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

        jfc.setSelectedFile(suggSchemaFile);

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

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

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

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

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

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

From source file:com.commander4j.db.JDBUserReport.java

private String promptUserforSave() {
    JFileChooser saveTYPE = new JFileChooser();
    String filename = getExportFilename();
    if (isPromptSaveAsRequired()) {

        try {/*from   www . java 2 s.c o m*/
            File f = new File(new File(getExportFilename()).getCanonicalPath());
            saveTYPE.setCurrentDirectory(f);
            if (getDestination().equals("EXCEL"))
                saveTYPE.addChoosableFileFilter(new JFileFilterXLS());
            if (getDestination().equals("JASPER_REPORT"))
                saveTYPE.addChoosableFileFilter(new JFileFilterPDF());
            if (getDestination().equals("PDF"))
                saveTYPE.addChoosableFileFilter(new JFileFilterPDF());
            if (getDestination().equals("CSV"))
                saveTYPE.addChoosableFileFilter(new JFileFilterCSV());
            if (getDestination().equals("ACCESS"))
                saveTYPE.addChoosableFileFilter(new JFileFilterMDB());
            saveTYPE.setSelectedFile(new File(getExportFilename()));

            int result = saveTYPE.showSaveDialog(Common.mainForm);
            if (result == 0) {
                File selectedFile;
                selectedFile = saveTYPE.getSelectedFile();
                if (selectedFile != null) {
                    filename = selectedFile.getAbsolutePath();
                }
            }
        } catch (Exception ex) {
        }
    }
    return filename;
}

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

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

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

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

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

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

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

From source file:org.pgptool.gui.ui.decryptone.DecryptOnePm.java

public SaveFileChooserDialog getTargetFileChooser() {
    if (targetFileChooser == null) {
        targetFileChooser = new SaveFileChooserDialog(findRegisteredWindowIfAny(), "action.chooseTargetFile",
                "action.choose", appProps, "DecryptionTargetChooser") {
            @Override//from  w  w  w.j a va 2 s . c  o m
            protected String onDialogClosed(String filePathName, JFileChooser ofd) {
                String ret = super.onDialogClosed(filePathName, ofd);
                if (ret != null) {
                    targetFile.setValueByOwner(ret);
                }
                return ret;
            }

            @Override
            protected void suggestTarget(JFileChooser ofd) {
                String sourceFileStr = sourceFile.getValue();
                if (StringUtils.hasText(targetFile.getValue())) {
                    // Case 1: Based on current target
                    use(ofd, targetFile.getValue());
                } else if (decryptionDialogParameters != null
                        && decryptionDialogParameters.getTargetFile() != null) {
                    if (decryptionDialogParameters.getSourceFile().equals(sourceFileStr)) {
                        // exact match
                        use(ofd, decryptionDialogParameters.getTargetFile());
                    } else {
                        // case when suggested parameters are provided for
                        // neighbor
                        use(ofd, madeUpTargetFileName(FilenameUtils
                                .getFullPathNoEndSeparator(decryptionDialogParameters.getTargetFile())));
                    }
                } else if (StringUtils.hasText(sourceFileStr) && new File(sourceFileStr).exists()) {
                    use(ofd, madeUpTargetFileName(FilenameUtils.getFullPathNoEndSeparator(sourceFileStr)));
                }
            }

            private void use(JFileChooser ofd, String filePathName) {
                ofd.setCurrentDirectory(new File(FilenameUtils.getFullPathNoEndSeparator(filePathName)));
                ofd.setSelectedFile(new File(filePathName));
            }
        };
    }
    return targetFileChooser;
}