Example usage for javax.swing JFileChooser getSelectedFile

List of usage examples for javax.swing JFileChooser getSelectedFile

Introduction

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

Prototype

public File getSelectedFile() 

Source Link

Document

Returns the selected file.

Usage

From source file:net.sf.keystore_explorer.gui.dialogs.DViewCertCsrPem.java

private void exportPressed() {
    File chosenFile = null;/*w  w  w  .  j  a  v a  2 s. c o m*/
    FileWriter fw = null;

    String title;
    if (cert != null) {
        title = res.getString("DViewCertCsrPem.ExportPemCertificate.Title");
    } else {
        title = res.getString("DViewCertCsrPem.ExportPemCsr.Title");
    }
    try {
        String certPem = jtaPem.getText();

        JFileChooser chooser = FileChooserFactory.getX509FileChooser();
        chooser.setCurrentDirectory(CurrentDirectory.get());
        chooser.setDialogTitle(title);
        chooser.setMultiSelectionEnabled(false);

        int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
                : chooser.showDialog(this, res.getString("DViewCertCsrPem.ChooseExportFile.button"));

        if (rtnValue != JFileChooser.APPROVE_OPTION) {
            return;
        }

        chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);

        if (chosenFile.isFile()) {
            String message = MessageFormat.format(res.getString("DViewCertCsrPem.OverWriteFile.message"),
                    chosenFile);

            int selected = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION);
            if (selected != JOptionPane.YES_OPTION) {
                return;
            }
        }

        fw = new FileWriter(chosenFile);
        fw.write(certPem);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this,
                MessageFormat.format(res.getString("DViewCertCsrPem.NoWriteFile.message"), chosenFile), title,
                JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(this, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fw);
    }

    JOptionPane.showMessageDialog(this, res.getString("DViewCertCsrPem.ExportPemCertificateSuccessful.message"),
            title, JOptionPane.INFORMATION_MESSAGE);
}

From source file:AST.DesignPatternDetection.java

private void btProgramPathActionPerformed(ActionEvent e) {
    // TODO add your code here
    JFileChooser f2 = new JFileChooser();
    f2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    f2.showDialog(null, null);/*from w  w  w  . ja  v  a2s  .c  o  m*/
    tfProgramPath.setText(f2.getSelectedFile().toString());
    //System.out.println(f.getCurrentDirectory());
    //System.out.println(f.getSelectedFile());
}

From source file:net.sf.maltcms.chromaui.project.spi.wizard.DBProjectVisualPanel1.java

private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
    String command = evt.getActionCommand();
    if ("BROWSE".equals(command)) {
        FileChooserBuilder fcb = new FileChooserBuilder(DBProjectVisualPanel1.class);
        fcb.setTitle("Select Project Location");
        fcb.setDirectoriesOnly(true);//from  ww  w.ja  v  a2 s.com
        String path = this.projectLocationTextField.getText();
        JFileChooser jfc = fcb.createFileChooser();
        if (path.length() > 0) {
            File f = new File(path);
            if (f.exists()) {
                jfc.setSelectedFile(f);
            }
        }
        if (JFileChooser.APPROVE_OPTION == jfc.showOpenDialog(this)) {
            File projectDir = jfc.getSelectedFile();
            projectLocationTextField.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
        }
        firePropertyChange("VALIDATE", null, null);
    }

}

From source file:edu.ku.brc.specify.tasks.AttachmentsTask.java

/**
 * //from w ww  . ja v  a 2  s. c  o  m
 */
private void exportAttachment(final CommandAction cmdAction) {
    exportFile = null;
    Object data = cmdAction.getData();
    if (data instanceof ImageDataItem) {
        ImageDataItem idi = (ImageDataItem) data;
        System.out.println(idi.getImgName());

        String origFilePath = BasicSQLUtils.querySingleObj(
                "SELECT OrigFilename FROM attachment WHERE AttachmentID = " + idi.getAttachmentId());
        if (StringUtils.isNotEmpty(origFilePath)) {
            origFilePath = FilenameUtils.getName(origFilePath);
        } else {
            origFilePath = idi.getTitle();
        }
        String usrHome = System.getProperty("user.home");
        JFileChooser dlg = new JFileChooser(usrHome);
        dlg.setSelectedFile(new File(origFilePath));
        int rv = dlg.showSaveDialog((Frame) UIRegistry.getTopWindow());
        if (rv == JFileChooser.APPROVE_OPTION) {
            File file = dlg.getSelectedFile();
            if (file != null) {
                String fullPath = file.getAbsolutePath();
                String oldExt = FilenameUtils.getExtension(origFilePath);
                String newExt = FilenameUtils.getExtension(fullPath);
                if (StringUtils.isEmpty(newExt) && StringUtils.isNotEmpty(oldExt)) {
                    fullPath += "." + oldExt;
                    exportFile = new File(fullPath);
                } else {
                    exportFile = file;
                }
                boolean isOK = true;
                if (exportFile.exists()) {
                    isOK = UIRegistry.displayConfirmLocalized("ATTCH.FILE_EXISTS", "ATTCH.REPLACE_MSG",
                            "ATTCH.REPLACE", "CANCEL", JOptionPane.QUESTION_MESSAGE);
                }
                if (isOK) {
                    ImageLoader loader = new ImageLoader(idi.getImgName(), idi.getMimeType(), true, -1, this);
                    ImageLoaderExector.getInstance().loadImage(loader);
                }
            }
            System.out.println(file.toPath());
        }
    }
}

From source file:org.pmedv.jake.commands.AddFilesCommand.java

@Override
public void execute() {

    final ApplicationContext ctx = AppContext.getApplicationContext();
    final ApplicationWindow win = (ApplicationWindow) ctx.getBean(BeanDirectory.WINDOW_APPLICATION);

    /**/*from  w  w w.  j a  v  a  2 s .c o m*/
     * Get last selected folder to simplify file browsing
     */

    if (AppContext.getLastSelectedFolder() == null)
        AppContext.setLastSelectedFolder(System.getProperty("user.home"));

    JFileChooser fc = new JFileChooser(AppContext.getLastSelectedFolder());
    fc.setDialogTitle("Add files");
    fc.setMultiSelectionEnabled(true);
    fc.setFileFilter(new MP3Filter());

    int result = fc.showOpenDialog(win);

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    File[] files = fc.getSelectedFiles();

    PlayerView view = JakeUtil.getCurrentActivePlayer();

    if (view == null) {

        ArrayList<File> fileList = new ArrayList<File>();

        for (int i = 0; i < files.length; i++)
            fileList.add(files[i]);

        final PlayerController controller = new PlayerController(fileList);
        JakeUtil.updateRecentFiles(fc.getSelectedFile().getAbsolutePath());
        AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

        View v = new View(fc.getSelectedFile().getAbsolutePath(), null, controller.getPlayerView());

        v.addListener(new DockingWindowAdapter() {

            @Override
            public void windowClosing(DockingWindow arg0) throws OperationAbortedException {

                controller.getPlayer().close();
                controller.getPlayFileCommand().setPlaying(false);
            }

        });

        openEditor(v);
    }

    else {

        if (files.length >= 1) {

            AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());
            JakeUtil.updateRecentFiles(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

            FileTableModel model = (FileTableModel) view.getFileTable().getModel();

            for (int i = 0; i < files.length; i++) {
                model.addObject(files[i]);
            }

        }

    }

}

From source file:view.FramePrincipal.java

public String retornaDiretorioArquivo(String[] TipoArquivo) {
    String dir = "";
    JFileChooser _fileChooser = new JFileChooser();

    int retval = _fileChooser.showOpenDialog(this);
    final String[] okFileExtensions = TipoArquivo;
    File file;/*  w  w w.j  a va2 s .co m*/
    if (retval == JFileChooser.APPROVE_OPTION) {
        file = _fileChooser.getSelectedFile();
        Boolean flag = false;

        for (String extension : okFileExtensions) {
            if (file.getName().toLowerCase().endsWith(extension)) {
                flag = true;
            }
        }
        if (!flag) {
            JOptionPane.showMessageDialog(this,
                    "Selecione um Arquivo do tipo " + java.util.Arrays.toString(TipoArquivo), "Erro",
                    JOptionPane.ERROR_MESSAGE);
            retornaDiretorioArquivo(TipoArquivo);
        }

        if (_fileChooser.getSelectedFile().exists()) {
            dir = _fileChooser.getSelectedFile().toString();
        }
        LimpaPanels();
    }
    return dir;
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Ask the user for a certain file path/*from   w w  w .ja v  a2s.  c om*/
 * 
 * @param chooser the {@link JFileChooser} to use
 * @param filter the file filter
 * @param title the title of the dialog
 * 
 * @return the selected file or null
 */
private String askForPath(JFileChooser chooser, FileFilter filter, String title) {
    chooser.setDialogTitle(title);
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile().getAbsolutePath();
    }

    return null;
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveReferenceXML() {
    JFileChooser chooser = new JFileChooser(
            "Save as alignment xml format. YOUR EVALUATION WILL NOT BE SAVED, ONLY A COPY OF THE INPUT.");
    chooser.setCurrentDirectory(new File("."));
    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && (JOptionPane.showConfirmDialog(frame,
                "File already exists. Overwrite?") != JOptionPane.YES_OPTION)) {
            return;
        }/*from w  ww  .  ja  va  2  s .  c  o  m*/
        frame.saveReferenceXML(chooser.getSelectedFile(), true);
    }
}

From source file:net.pandoragames.far.ui.swing.menu.FileMenu.java

private void init(final Localizer localizer, final ComponentRepository componentRepository) {
    //   Import/*from w  ww  . j a  v a  2 s . co  m*/
    JMenuItem importMenu = new JMenuItem(localizer.localize("label.import"));
    importMenu.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser(config.getFileListExportDirectory());
            fileChooser.setDialogTitle(localizer.localize("label.select-import-file"));
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = fileChooser.showOpenDialog(FileMenu.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                Runnable fileImporter = new ImportAction(fileChooser.getSelectedFile(), localizer,
                        componentRepository.getOperationCallBackListener(), config.isWindows());
                Thread thread = new Thread(fileImporter);
                thread.setDaemon(true);
                thread.start();
            }
        }
    });
    this.add(importMenu);
    //   Export
    export = new JMenuItem(localizer.localize("label.export"));
    export.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ExportFileListDialog dialog = new ExportFileListDialog(mainFrame, tableModel, config);
            dialog.pack();
            dialog.setVisible(true);
        }
    });
    this.add(export);
    // seperator 
    this.addSeparator();
    //   Edit
    edit = new JMenuItem(localizer.localize("label.edit"));
    edit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileEditor editor = new FileEditor(mainFrame, tableModel.getSelectedRows().get(0), config);
            editor.pack();
            editor.setVisible(true);
        }
    });
    this.add(edit);
    //   View
    JMenuItem view = new JMenuItem(viewAction);
    this.add(view);
    //   Preview
    JMenuItem preview = new JMenuItem(previewAction);
    this.add(preview);
    //   Info
    info = new JMenuItem(localizer.localize("label.info"));
    info.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            InfoView infoView = new InfoView(mainFrame, tableModel.getSelectedRows().get(0), config,
                    repository);
            infoView.pack();
            infoView.setVisible(true);
        }
    });
    this.add(info);
    // seperator 
    this.addSeparator();
    // copy
    copy = new JMenuItem(localizer.localize("menu.copy"));
    copy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.copyDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(copy);
    // tree copy
    treeCopy = new JMenuItem(localizer.localize("menu.treeCopy"));
    treeCopy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.treeCopyDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(treeCopy);
    // move
    move = new JMenuItem(localizer.localize("menu.move"));
    move.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.moveDialog(tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(move);
    // delete
    delete = new JMenuItem(localizer.localize("menu.delete"));
    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FileOperationDialog.deleteDialog(tableModel, findForm.getBaseDirectory(), errorSink, config,
                    mainFrame);
        }
    });
    this.add(delete);
    // rename
    rename = new JMenuItem(localizer.localize("menu.rename-dialog"));
    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int rowIndex = tableModel.getRowIndex(tableModel.getSelectedRows().get(0));
            FileOperationDialog.renameDialog(rowIndex, tableModel, findForm, errorSink, config, mainFrame);
        }
    });
    this.add(rename);
}

From source file:com.smanempat.controller.ControllerClassification.java

public void chooseFile(ActionEvent evt, JTextField txtFileDirectory, JTextField txtNumberOfK,
        JLabel labelJumlahData, JButton buttonProses, JTable tablePreview) {
    try {/*from   w ww . ja v a2  s .c  om*/
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Excel File", "xls",
                "xlsx");
        fileChooser.setFileFilter(fileNameExtensionFilter);

        if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
            txtFileDirectory.setText(fileChooser.getSelectedFile().getAbsolutePath());
            System.out.println("Good, File Chooser runing well!");
            if (txtFileDirectory.getText().endsWith(".xls") || txtFileDirectory.getText().endsWith(".xlsx")) {
                showOnTable(evt, txtFileDirectory, tablePreview);
                labelJumlahData.setText(tablePreview.getRowCount() + " Data");
                txtNumberOfK.setEnabled(true);
                txtNumberOfK.requestFocus();
                buttonProses.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null,
                        "File dataset harus file spreadsheet dengan ekstensi *xls atau *.xlsx!", "Error",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon("src/com/smanempat/image/fail.png"));
                txtFileDirectory.setText("");
                chooseFile(evt, txtFileDirectory, txtNumberOfK, labelJumlahData, buttonProses, tablePreview);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}