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:org.nekorp.workflow.desktop.view.EvidenciaEventoView.java

private void nuevaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevaActionPerformed
    try {/*from  ww  w  .ja  v a  2  s  . co  m*/
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Imagen", "jpg", "jpeg", "png");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        File f = new File(new File(homePath).getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showOpenDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            BufferedImage img = ImageIO.read(chooser.getSelectedFile());
            img = imageService.resizeToStandarSize(img);
            BufferedImage thumb = imageService.getThumbnail(img);
            EvidenciaVB nuevaEvidencia = new EvidenciaVB();
            nuevaEvidencia.setImage(imageService.guardarImagen(img));
            nuevaEvidencia.setThumbnail(imageService.guardarImagen(thumb));
            ThumbnailView thumbview = new ThumbnailView(thumb, this);
            thumbview.setEditableStatus(editable);
            thumbs.add(thumbview);
            modelo.add(nuevaEvidencia);
            previewContent.add(thumbview);
            this.ignore.add(modelo);
            actualizaModelo();
            selectEvent(thumbview);
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
    } catch (IOException ex) {
        EvidenciaEventoView.LOGGER.error("Error al seleccionar archivo de imagen", ex);
    }
}

From source file:storybook.ui.chart.AbstractChartPanel.java

private AbstractAction getExportAction() {
    if (this.exportAction == null) {
        this.exportAction = new AbstractAction() {
            @Override/*from  w w  w . j a  v a 2s  .  co m*/
            public void actionPerformed(ActionEvent paramAnonymousActionEvent) {
                try {
                    Internal localInternal = BookUtil.get(AbstractChartPanel.this.mainFrame,
                            SbConstants.BookKey.EXPORT_DIRECTORY,
                            EnvUtil.getDefaultExportDir(AbstractChartPanel.this.mainFrame));
                    File localFile1 = new File(localInternal.getStringValue());
                    JFileChooser localJFileChooser = new JFileChooser(localFile1);
                    localJFileChooser.setFileFilter(new PngFileFilter());
                    localJFileChooser.setApproveButtonText(I18N.getMsg("msg.common.export"));
                    String str = AbstractChartPanel.this.mainFrame.getDbFile().getName() + " - "
                            + AbstractChartPanel.this.chartTitle;
                    str = IOUtil.cleanupFilename(str);
                    localJFileChooser.setSelectedFile(new File(str));
                    int i = localJFileChooser.showDialog(AbstractChartPanel.this.getThis(),
                            I18N.getMsg("msg.common.export"));
                    if (i == 1) {
                        return;
                    }
                    File localFile2 = localJFileChooser.getSelectedFile();
                    if (!localFile2.getName().endsWith(".png")) {
                        localFile2 = new File(localFile2.getPath() + ".png");
                    }
                    ScreenImage.createImage(AbstractChartPanel.this.panel, localFile2.toString());
                    JOptionPane.showMessageDialog(AbstractChartPanel.this.getThis(),
                            I18N.getMsg("msg.common.export.success"), I18N.getMsg("msg.common.export"), 1);
                } catch (HeadlessException | IOException localException) {
                }
            }
        };
    }
    return this.exportAction;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.area.AreaDoseResponseController.java

/**
 * Ask user to choose for a directory and invoke swing worker for creating
 * PDF report/*from   w w w.  ja  v a 2 s .  co m*/
 *
 * @throws IOException
 */
protected void createPdfReport() throws IOException {
    Experiment experiment = areaMainController.getExperiment();
    // choose directory to save pdf file
    JFileChooser chooseDirectory = new JFileChooser();
    chooseDirectory.setDialogTitle("Choose a directory to save the report");
    chooseDirectory.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooseDirectory.setSelectedFile(new File("Dose Response Report " + experiment.toString() + " - "
            + experiment.getProject().toString() + ".pdf"));
    // in response to the button click, show open dialog
    int returnVal = chooseDirectory.showSaveDialog(areaMainController.getDataAnalysisPanel());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File directory = chooseDirectory.getCurrentDirectory();
        DoseResponseReportSwingWorker doseResponseReportSwingWorker = new DoseResponseReportSwingWorker(
                directory, chooseDirectory.getSelectedFile().getName());
        doseResponseReportSwingWorker.execute();
    } else {
        areaMainController.showMessage("Open command cancelled by user", "", JOptionPane.INFORMATION_MESSAGE);
    }
}

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

/**
 * /*  w w w  .ja va 2 s .  co 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.nekorp.workflow.desktop.view.AppLayoutView.java

private void reporteGlobalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reporteGlobalButtonActionPerformed
    try {//from  www. ja  va 2s  .  c  om
        parametrosReporteGlobal.setFechaInicial(new Date());
        parametrosReporteGlobal.setFechaFinal(new Date());
        parametrosReporteGlobalDialogFactory.createDialog(mainFrame, true).setVisible(true);
        if (parametrosReporteGlobal.isEjecutar()) {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Hojas de clculo", "xlsx");
            chooser.setFileFilter(filter);
            String homePath = System.getProperty("user.home");
            File f = new File(new File(homePath + "/Reporte-Global" + ".xlsx").getCanonicalPath());
            chooser.setSelectedFile(f);
            int returnVal = chooser.showSaveDialog(this.mainFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
                ParametrosReporteGlobal param = new ParametrosReporteGlobal();
                param.setDestination(chooser.getSelectedFile());
                DateTime fechaInicial = new DateTime(parametrosReporteGlobal.getFechaInicial());
                DateTime fechaFinal = new DateTime(parametrosReporteGlobal.getFechaFinal());
                fechaFinal = new DateTime(fechaFinal.getYear(), fechaFinal.getMonthOfYear(),
                        fechaFinal.getDayOfMonth(), fechaFinal.hourOfDay().getMaximumValue(),
                        fechaFinal.minuteOfHour().getMaximumValue(),
                        fechaFinal.secondOfMinute().getMaximumValue(),
                        fechaFinal.millisOfSecond().getMaximumValue(), fechaFinal.getZone());
                param.setFechaInicial(fechaInicial);
                param.setFechaFinal(fechaFinal);
                this.aplication.generaReporteGlobal(param);
            }
        }
    } catch (IOException ex) {
        AppLayoutView.LOGGER.error("Exploto al tratar de generar el reporte global", ex);
    } finally {
        this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    }
}

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 w w w .  j  av  a 2  s. co m
        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:de.ep3.ftpc.controller.portal.CrawlerDownloadController.java

@Override
public void mouseClicked(MouseEvent e) {
    CrawlerResultsItem.PreviewPanel previewPanel = (CrawlerResultsItem.PreviewPanel) e.getSource();
    CrawlerResult crawlerResult = previewPanel.getCrawlerResult();
    CrawlerFile crawlerFile = crawlerResult.getFile();

    FTPClient ftpClient = crawlerResult.getFtpClient();

    if (ftpClient.isConnected()) {
        JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadWhileConnected"), null,
                JOptionPane.ERROR_MESSAGE);
        return;/*  w w w .  j  ava2 s  .co m*/
    }

    String fileExtension = crawlerFile.getExtension();

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter chooserFilter = new FileNameExtensionFilter(
            i18n.translate("fileType", fileExtension.toUpperCase()), crawlerFile.getExtension());

    chooser.setApproveButtonText(i18n.translate("buttonSave"));
    chooser.setDialogTitle(i18n.translate("fileDownloadTo"));
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    chooser.setFileFilter(chooserFilter);
    chooser.setSelectedFile(new File(crawlerFile.getName()));

    int selection = chooser.showSaveDialog(portalFrame);

    if (selection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = chooser.getSelectedFile();

        Server relatedServer = crawlerResult.getServer();

        try {
            ftpClient.connect(relatedServer.need("server.ip"),
                    Integer.parseInt(relatedServer.need("server.port")));

            int replyCode = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new IOException(i18n.translate("crawlerServerRefused"));
            }

            if (relatedServer.has("user.name")) {
                String userName = relatedServer.get("user.name");
                String userPassword = "";

                if (relatedServer.hasTemporary("user.password")) {
                    userPassword = relatedServer.getTemporary("user.password");
                }

                boolean loggedIn = ftpClient.login(userName, userPassword);

                if (!loggedIn) {
                    throw new IOException(i18n.translate("crawlerServerAuthFail"));
                }
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            /* Download file */

            InputStream is = ftpClient.retrieveFileStream(crawlerFile.getFullName());

            if (is != null) {

                byte[] rawFile = new byte[(int) crawlerFile.getSize()];

                int i = 0;

                while (true) {
                    int b = is.read();

                    if (b == -1) {
                        break;
                    }

                    rawFile[i] = (byte) b;
                    i++;

                    /* Occasionally update the download progress */

                    if (i % 1024 == 0) {
                        int progress = Math.round((((float) i) / crawlerFile.getSize()) * 100);

                        status.add(i18n.translate("crawlerDownloadProgress", progress));
                    }
                }

                is.close();
                is = null;

                if (!ftpClient.completePendingCommand()) {
                    throw new IOException();
                }

                Files.write(fileToSave.toPath(), rawFile);
            }

            /* Logout and disconnect */

            ftpClient.logout();

            tryDisconnect(ftpClient);

            status.add(i18n.translate("crawlerDownloadDone"));
        } catch (IOException ex) {
            tryDisconnect(ftpClient);

            JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadFailed", ex.getMessage()),
                    null, JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:gui.InboxPanel.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    try {//  ww  w.j ava 2 s. c om
        String name = GmailAPI.getAttachmentFilename(curId);
        System.out.println(name);
        if (name == "None") {
            JOptionPane.showMessageDialog(this, "No file attached on this email");
        } else {
            JFileChooser chooser = new JFileChooser();
            File defFile = new File(name);
            chooser.setSelectedFile(defFile);
            int filesave = chooser.showSaveDialog(null);
            if (filesave == JFileChooser.APPROVE_OPTION) {
                //chooser.getSelectedFile().se
                File file = chooser.getCurrentDirectory();
                GmailAPI.getAttachments(GmailAPI.service, GmailAPI.USER, curId, file.getAbsolutePath(),
                        chooser.getSelectedFile().getName());
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(InboxPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.nekorp.workflow.desktop.view.CostoServicioView.java

private void generarReporteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generarReporteActionPerformed
    try {/*from ww  w.ja  v  a 2 s . co m*/
        if (servicioMetaData.isEditado()) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.aplication.guardaServicio();
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Hojas de clculo", "xlsx");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        File f = new File(new File(homePath + "/Reporte-Servicio-" + this.viewServicioModel.getId() + ".xlsx")
                .getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showSaveDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            ParametrosReporte param = new ParametrosReporte();
            param.setDestination(chooser.getSelectedFile());
            this.aplication.generaReporte(param);
        }
    } catch (IllegalArgumentException e) {
        //no lo guardo por que tenia horribles errores... tambien especializar la excepcion
    } catch (IOException ex) {
        CostoServicioView.LOGGER.error(ex);
    } finally {
        this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    }
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Persists out the timelord file and allows the user to choose where
 * the file should go./*from w w w  .j ava2  s. c  o m*/
 *
 * @param rwClassName the name of the RW class
 *        (e.g. "net.chaosserver.timelord.data.ExcelDataReaderWriter")
 * @param userSelect allows the user to select where the file should
 *        be persisted.
 */
public void writeTimeTrackData(String rwClassName, boolean userSelect) {
    try {
        Class<?> rwClass = Class.forName(rwClassName);
        TimelordDataReaderWriter timelordDataRW = (TimelordDataReaderWriter) rwClass.newInstance();

        int result = JFileChooser.APPROVE_OPTION;
        File outputFile = timelordDataRW.getDefaultOutputFile();

        if (timelordDataRW instanceof TimelordDataReaderWriterUI) {
            TimelordDataReaderWriterUI timelordDataReaderWriterUI = (TimelordDataReaderWriterUI) timelordDataRW;

            timelordDataReaderWriterUI.setParentFrame(applicationFrame);
            JDialog configDialog = timelordDataReaderWriterUI.getConfigDialog();

            configDialog.pack();
            configDialog.setLocationRelativeTo(applicationFrame);
            configDialog.setVisible(true);
        }

        if (userSelect) {
            if (OsUtil.isMac()) {
                FileDialog fileDialog = new FileDialog(applicationFrame, "Select File", FileDialog.SAVE);

                fileDialog.setDirectory(outputFile.getParent());
                fileDialog.setFile(outputFile.getName());
                fileDialog.setVisible(true);
                if (fileDialog.getFile() != null) {
                    outputFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
                }

            } else {
                JFileChooser fileChooser = new JFileChooser(outputFile.getParentFile());

                fileChooser.setSelectedFile(outputFile);
                fileChooser.setFileFilter(timelordDataRW.getFileFilter());
                result = fileChooser.showSaveDialog(applicationFrame);

                if (result == JFileChooser.APPROVE_OPTION) {
                    outputFile = fileChooser.getSelectedFile();
                }
            }
        }

        if (result == JFileChooser.APPROVE_OPTION) {
            timelordDataRW.writeTimelordData(getTimelordData(), outputFile);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(applicationFrame,
                "Error writing to file.\n" + "Do you have the output file open?", "Save Error",
                JOptionPane.ERROR_MESSAGE, applicationIcon);

        if (log.isErrorEnabled()) {
            log.error("Error persisting file", e);
        }
    }
}