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:plugins.tprovoost.Microscopy.MicroManagerForIcy.MMMainFrame.java

/**
 * Save the configuration presets. From Micro-Manager.
 *///from   w  w w .j a  va 2 s .c  o  m
protected void saveConfig() {
    MicroscopeModel model = new MicroscopeModel();
    try {
        model.loadFromFile(_sysConfigFile);
        model.createSetupConfigsFromHardware(mCore);
        model.createResolutionsFromHardware(mCore);
        JFileChooser fc = new JFileChooser();
        boolean saveFile = true;
        File f;
        do {
            fc.setSelectedFile(new File(model.getFileName()));
            int retVal = fc.showSaveDialog(null);
            if (retVal == 0) {
                f = fc.getSelectedFile();

                if (f.exists()) {
                    int sel = JOptionPane.showConfirmDialog(null, "Overwrite " + f.getName(), "File Save", 0);

                    if (sel == 0)
                        saveFile = true;
                    else
                        saveFile = false;
                }
            } else {
                return;
            }
        } while (!saveFile);

        model.saveToFile(f.getAbsolutePath());
        _sysConfigFile = f.getAbsolutePath();
        _configChanged_ = false;
        setConfigSaveButtonStatus(_configChanged_);
    } catch (MMConfigFileException e) {
        ReportingUtils.showError(e);
    }
}

From source file:processing.app.Base.java

static public File selectFolder(String prompt, File folder, Component parent) {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(prompt);/*from  w  w  w  .j  ava 2s . c  o m*/
    if (folder != null) {
        fc.setSelectedFile(folder);
    }
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int returned = fc.showOpenDialog(parent);
    if (returned == JFileChooser.APPROVE_OPTION) {
        return fc.getSelectedFile();
    }
    return null;
}

From source file:pt.lsts.neptus.mra.exporters.MRAExporterFilter.java

private File chooseSaveFile(String path) {
    JFileChooser fileChooser = GuiUtils.getFileChooser(path, I18n.text("LSF logs"), FileUtil.FILE_TYPE_LSF,
            FileUtil.FILE_TYPE_LSF_COMPRESSED, FileUtil.FILE_TYPE_LSF_COMPRESSED_BZIP2);
    fileChooser.setSelectedFile(new File(path.concat("/Data_filtered.lsf.gz")));
    fileChooser.setAcceptAllFileFilterUsed(false);

    int status = fileChooser.showSaveDialog(ConfigFetch.getSuperParentFrame());
    String fileName = null;//from www . j  a va2 s  . co m

    if (status == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();

        try {
            fileName = selectedFile.getCanonicalPath();
            if (fileName.endsWith("." + FileUtil.FILE_TYPE_LSF_COMPRESSED)
                    || fileName.endsWith("." + FileUtil.FILE_TYPE_LSF_COMPRESSED_BZIP2)) {
                return selectedFile = new File(fileName);
            }
            if (!fileName.endsWith("." + FileUtil.FILE_TYPE_LSF)) {
                return selectedFile = new File(fileName + "." + FileUtil.FILE_TYPE_LSF_COMPRESSED);
            }
            if (fileName.endsWith("." + FileUtil.FILE_TYPE_LSF)) {
                return selectedFile = new File(fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:qrcode.JavaQR.java

@Override
public void run() {

    setLayout(new BorderLayout());

    JPanel topPanel = new JPanel();
    JPanel centerPanel = new JPanel();
    JPanel bottomPanel = new JPanel();

    topPanel.setLayout(new GridLayout(0, 1));
    topPanel.setBorder(BorderFactory.createTitledBorder("Input Data"));

    JPanel rowTopPanel = new JPanel();
    rowTopPanel.setLayout(new GridLayout(0, 2));

    JLabel accKey = new JLabel("Access Key");
    JTextField accField = new JTextField(5);

    accField.setEditable(false);/*from  w  w  w.  jav  a2s  .  co  m*/
    accField.setText(Data.accessKey);

    JLabel regNo = new JLabel("Registration Number");
    JTextField regField = new JTextField(5);

    regField.setEditable(false);
    regField.setText(Data.registrationNumber);

    JLabel licNo = new JLabel("License Number");
    JFormattedTextField licField = new JFormattedTextField();

    licField.setEditable(false);
    licField.setText(Data.licenseNumber);

    rowTopPanel.add(accKey);
    rowTopPanel.add(accField);
    rowTopPanel.add(regNo);
    rowTopPanel.add(regField);
    rowTopPanel.add(licNo);
    rowTopPanel.add(licField);

    topPanel.add(rowTopPanel);

    centerPanel.setLayout(new GridLayout(0, 1));
    centerPanel.setBorder(BorderFactory.createTitledBorder("QR Code"));

    JPanel rowCenPanel = new JPanel();
    rowCenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

    JButton genBtn = new JButton("Download QR Code");
    JButton homeBtn = new JButton("Back to Start");

    String accessKey = accField.getText().toString();
    String regKey = regField.getText().toString();
    String licKey = licField.getText().toString();
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("accessKey", accessKey);
        jsonObject.put("registrationNumber", regKey);
        jsonObject.put("licenseNumber", licKey);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    QRLogic qrGen = new QRLogic();
    BufferedImage image = qrGen.generateQR(jsonObject);
    centerPanel.add(new JLabel(new ImageIcon(image)));

    bottomPanel.setLayout(new GridLayout(2, 1));

    rowCenPanel.add(homeBtn);
    rowCenPanel.add(genBtn);
    bottomPanel.add(rowCenPanel);
    add(topPanel, BorderLayout.NORTH);
    add(bottomPanel, BorderLayout.SOUTH);
    add(centerPanel, BorderLayout.CENTER);
    Data.mainFrame.setSize(1000, 500);

    genBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Date date = new Date();
            String newDate = new SimpleDateFormat("yyyy-MM-dd h-m-a").format(date);
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            File myFile = new File(Data.registrationNumber + ".png");
            fileChooser.setSelectedFile(myFile);
            fileChooser.showSaveDialog(null);
            String dlDir = fileChooser.getSelectedFile().getPath();
            System.out.println(dlDir);
            String fileName = fileChooser.getSelectedFile().getName();
            String filePath = "";
            if (fileName != null) {
                filePath = dlDir + ".png";
            } else {
                filePath = dlDir + "/" + Data.registrationNumber + ".png";
            }

            String fileType = "png";
            myFile = new File(filePath);

            if (dlDir != null) {

                try {
                    ImageIO.write(image, fileType, myFile);
                    JOptionPane.showMessageDialog(Data.mainFrame, "QR Code Saved in " + dlDir);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }
    });

    homeBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.showPanel("inventory");
        }
    });

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    } catch (UnsupportedLookAndFeelException e1) {
        e1.printStackTrace();
    }

}

From source file:ru.goodfil.catalog.ui.forms.MainWindow.java

/**
 *  /*from w ww.  ja  v  a2s  .c  o m*/
 *
 * @param e
 */
private void saveAsMenuItemActionPerformed(ActionEvent e) {
    try {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setSelectedFile(new File(new File("~/GoodwillCatalog.h2.db").getCanonicalPath()));
        fileChooser.setFileFilter(new FileNameExtensionFilter(" (*.h2.db)", "db"));
        int result = fileChooser.showSaveDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            File destinationFile = fileChooser.getSelectedFile();

            if (destinationFile != null) {
                sessionProvider.close();

                File database = new File(SessionFactoryHolder.getDatabasePathWithPrefix());

                try {
                    FileUtils.copyFile(database, destinationFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                    UIUtils.error("? ? ? !");
                }

                sessionProvider.init();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
}

From source file:sc.fiji.kappa.gui.CurvesExporter.java

public void export(boolean exportAveragePerCurve) throws IOException {

    JFileChooser kappaExport = new JFileChooser();

    String dirPath = frame.getImageStack().getOriginalFileInfo().directory;
    if (dirPath != null) {
        String kappaPath = FilenameUtils.removeExtension(frame.getImageStack().getOriginalFileInfo().fileName);
        kappaPath += ".csv";
        File fullPath = new File(dirPath, kappaPath);
        kappaExport.setSelectedFile(fullPath);
    }//w ww. j a v  a  2 s.  com

    kappaExport.setFileFilter(new FileNameExtensionFilter("CSV File", "csv"));
    kappaExport.setDialogTitle("Export Curve Data");

    // Handles export button action.
    int returnVal = kappaExport.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = kappaExport.getSelectedFile();
        exportToFile(file, exportAveragePerCurve);
    }
}

From source file:se.cambio.cds.gdl.editor.controller.GDLEditor.java

public void saveCompiledGuideAsObject(byte[] compiledGuide, Guide guide) {
    GDLEditor controller = EditorManager.getActiveGDLEditor();
    String idGuide = controller.getIdGuide();
    if (idGuide == null) {
        idGuide = GDLEditorLanguageManager.getMessage("Guide");
    }/*from  w w w .j  av  a  2  s. c om*/
    if (compiledGuide != null) {
        try {
            String guideSource = controller.serializeCurrentGuide();
            if (guideSource != null) {
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        GDLEditorLanguageManager.getMessage("Guide"), new String[] { "guide" });
                fileChooser.setDialogTitle(GDLEditorLanguageManager.getMessage("SaveGuideAsObjectSD"));
                fileChooser.setFileFilter(filter);
                File file = new File(
                        fileChooser.getFileSystemView().getDefaultDirectory() + "/" + idGuide + ".guide");
                fileChooser.setSelectedFile(file);
                int result = fileChooser.showSaveDialog(EditorManager.getActiveEditorWindow());
                File guideFile = fileChooser.getSelectedFile();
                if (result != JFileChooser.CANCEL_OPTION) {
                    idGuide = guideFile.getName();
                    if (idGuide.endsWith(".guide")) {
                        idGuide = idGuide.substring(0, idGuide.length() - 6);
                    }
                    GuideDTO guideDTO = new GuideDTO(idGuide, guideSource, IOUtils.getBytes(guide),
                            compiledGuide, true, Calendar.getInstance().getTime());
                    ObjectOutputStream output = new ObjectOutputStream(
                            new BufferedOutputStream(new FileOutputStream(guideFile)));
                    try {
                        output.writeObject(guideDTO);
                    } catch (Exception e) {
                        ExceptionHandler.handle(e);
                    } finally {
                        output.close();
                    }
                }
            }
        } catch (Exception e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:se.cambio.cds.util.ExportUtils.java

public static void exportToHTML(Window owner, Guide guide, String lang) {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", new String[] { "html" });
    fileChooser.setDialogTitle(OpenEHRLanguageManager.getMessage("ExportToHTML"));
    fileChooser.setFileFilter(filter);//w w w. j  a  va2 s  .  c  om
    File selectedFile = new File(guide.getId() + ".html");
    fileChooser.setSelectedFile(selectedFile);
    int result = fileChooser.showSaveDialog(owner);
    if (result != JFileChooser.CANCEL_OPTION) {
        try {
            selectedFile = fileChooser.getSelectedFile();
            FileWriter fstream = new FileWriter(selectedFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(convertToHTML(guide, lang));
            out.close();
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (InternalErrorException e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:su.fmi.photoshareclient.ui.PhotoViewDialog.java

private void SaveImageButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveImageButtonMouseClicked
    JFileChooser fileChooser = new JFileChooser() {
        // A warning for overweiting existing files
        @Override/*from  ww  w  .  j  a v  a 2s  .com*/
        public void approveSelection() {
            File f = getSelectedFile();
            if (f.exists() && getDialogType() == SAVE_DIALOG) {
                int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?", "Existing file",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                switch (result) {
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
                    return;
                case JOptionPane.NO_OPTION:
                    return;
                case JOptionPane.CLOSED_OPTION:
                    return;
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
                    return;
                }
            }
            super.approveSelection();
        }
    };
    fileChooser.setDialogTitle("Save image as...");
    File rootVolume = File.listRoots()[0];
    fileChooser.setSelectedFile(new File(rootVolume.getAbsolutePath(), this.imageLabel.getFileName()));

    int userSelection = fileChooser.showSaveDialog(this);

    if (userSelection == JFileChooser.APPROVE_OPTION) {
        try {
            File fileToSave = fileChooser.getSelectedFile();
            BufferedImage bi = (BufferedImage) this.imageLabel.getImage();
            String ext = FilenameUtils.getExtension(fileToSave.getAbsolutePath());
            ImageIO.write(bi, ext, fileToSave);
        } catch (IOException ex) {
            Logger.getLogger(PhotoViewDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Open or create a SQL statement file./* w  w w .  j av a  2  s .  c  om*/
 */
private void openSQLFile() {
    JFileChooser fileMenu;
    FileFilter defaultFileFilter = null;
    FileFilter preferredFileFilter = null;
    File chosenSQLFile;
    int returnVal;

    chosenSQLFile = null;

    // Save current information, including SQL Statements
    saveConfig();

    // Allow user to choose/create new file for SQL Statements
    fileMenu = new JFileChooser(new File(queryFilename));

    for (FileFilterDefinition filterDefinition : FileFilterDefinition.values()) {
        if (filterDefinition.name().startsWith("QUERY")) {
            final FileFilter fileFilter = new SuffixFileFilter(filterDefinition.description(),
                    filterDefinition.acceptedSuffixes());
            if (filterDefinition.isPreferredOption()) {
                preferredFileFilter = fileFilter;
            }
            fileMenu.addChoosableFileFilter(fileFilter);
            if (filterDefinition.description().equals(latestChosenQueryFileFilterDescription)) {
                defaultFileFilter = fileFilter;
            }
        }
    }

    if (defaultFileFilter != null) {
        fileMenu.setFileFilter(defaultFileFilter);
    } else if (latestChosenQueryFileFilterDescription != null
            && latestChosenQueryFileFilterDescription.startsWith("All")) {
        fileMenu.setFileFilter(fileMenu.getAcceptAllFileFilter());
    } else if (preferredFileFilter != null) {
        fileMenu.setFileFilter(preferredFileFilter);
    }

    fileMenu.setSelectedFile(new File(queryFilename));
    fileMenu.setDialogTitle(Resources.getString("dlgSQLFileTitle"));
    fileMenu.setDialogType(JFileChooser.OPEN_DIALOG);
    fileMenu.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileMenu.setMultiSelectionEnabled(false);

    if (fileMenu.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        chosenSQLFile = fileMenu.getSelectedFile();

        // Adjust file suffix if necessary
        final FileFilter fileFilter = fileMenu.getFileFilter();
        if (fileFilter != null && fileFilter instanceof SuffixFileFilter
                && !fileMenu.getFileFilter().accept(chosenSQLFile)) {
            chosenSQLFile = ((SuffixFileFilter) fileFilter).makeWithPrimarySuffix(chosenSQLFile);
        }

        if (!chosenSQLFile.exists()) {
            returnVal = JOptionPane.showConfirmDialog(this,
                    Resources.getString("dlgNewSQLFileText", chosenSQLFile.getName()),
                    Resources.getString("dlgNewSQLFileTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (returnVal == JOptionPane.NO_OPTION) {
                querySelection.removeAllItems();
                queryText.setText("");
                QueryHistory.getInstance().clearAllQueries();

                // Update GUI
                setPrevNextIndication();
            } else if (returnVal == JOptionPane.CANCEL_OPTION) {
                chosenSQLFile = null;
            }
        } else {
            setQueryFilename(chosenSQLFile.getAbsolutePath());
            querySelection.removeAllItems();
            queryText.setText("");
            loadCombo(querySelection, queryFilename);
            QueryHistory.getInstance().clearAllQueries();

            // Update GUI
            setPrevNextIndication();
        }
    }

    try {
        latestChosenQueryFileFilterDescription = fileMenu.getFileFilter().getDescription();
    } catch (Throwable throwable) {
        LOGGER.warn("Unable to determine which ontology file filter was chosen", throwable);
    }

    if (chosenSQLFile != null) {
        setQueryFilename(chosenSQLFile.getAbsolutePath());
        saveConfig();
    }
}