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:io.github.jeremgamer.editor.panels.IconFrame.java

public IconFrame(JFrame parent) {
    this.setModal(true);
    this.setResizable(false);
    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//from   w w w .  j a va  2  s.co m
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png")));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    this.setIconImages((List<? extends Image>) icons);
    this.setTitle("Icnes");

    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    JPanel content = new JPanel();
    content.setLayout(new BoxLayout(content, BoxLayout.LINE_AXIS));
    content.setBorder(BorderFactory.createTitledBorder(""));

    try {
        remove128.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        remove64.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        remove32.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        remove16.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    browse128.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "128.png");
                try {
                    x128.repaint();
                    x128.getGraphics().drawImage(ImageIO.read(new File(path)), 0 + 10, 0 + 20, 128, 128, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    remove128.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File("projects/" + Editor.getProjectName() + "/128.png");
            file.delete();
            x128.repaint();
        }
    });
    browse64.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "64.png");
                try {
                    x64.repaint();
                    x64.getGraphics().drawImage(ImageIO.read(new File(path)), 32 + 10, 32 + 20, 64, 64, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    remove64.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File("projects/" + Editor.getProjectName() + "/64.png");
            file.delete();
            x64.repaint();
        }
    });
    browse32.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "32.png");
                try {
                    x32.repaint();
                    x32.getGraphics().drawImage(ImageIO.read(new File(path)), 48 + 10, 48 + 20, 32, 32, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    remove32.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File("projects/" + Editor.getProjectName() + "/32.png");
            file.delete();
            x32.repaint();
        }
    });
    browse16.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            String path = null;
            JFileChooser chooser = new JFileChooser(Editor.lastPath);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "png", "gif", "jpeg",
                    "bmp");
            chooser.setFileFilter(filter);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int option = chooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                path = chooser.getSelectedFile().getAbsolutePath();
                Editor.lastPath = chooser.getSelectedFile().getParent();
                copyImage(new File(path), "16.png");
                try {
                    x16.repaint();
                    x16.getGraphics().drawImage(ImageIO.read(new File(path)), 56 + 10, 56 + 20, 16, 16, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    remove16.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            File file = new File("projects/" + Editor.getProjectName() + "/16.png");
            file.delete();
            x16.repaint();
        }
    });

    content.add(x128);
    content.add(x64);
    content.add(x32);
    content.add(x16);
    this.setContentPane(content);
    this.pack();
    this.setLocationRelativeTo(parent);
    this.setVisible(true);
}

From source file:coreferenceresolver.gui.MainGUI.java

private void trainingBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_trainingBtnActionPerformed
    // TODO add your handling code here:
    JFileChooser inputFileChooser = new JFileChooser(defaulPath);
    inputFileChooser.setDialogTitle("Choose where your training file saved");
    inputFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    if (inputFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        trainingFilePathTF/* w  w w .  j  av  a 2  s  .  com*/
                .setText(inputFileChooser.getSelectedFile().getAbsolutePath() + File.separator + "train.arff");
        noteTF.setText("Create training file waiting ...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TrainingMain.run(inputFilePathTF.getText(), markupFilePathTF.getText(),
                            trainingFilePathTF.getText(), true);
                    noteTF.setText("Create training file done!");
                    String folderPathOpen = trainingFilePathTF.getText().substring(0,
                            trainingFilePathTF.getText().lastIndexOf(File.separatorChar));
                    Desktop.getDesktop().open(new File(folderPathOpen));
                } catch (Exception ex) {
                    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    } else {
        noteTF.setText("No training file location selected");
    }
}

From source file:net.sf.mzmine.chartbasics.gui.swing.EChartPanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart in PNG format.
 *
 * @throws IOException if there is an I/O error.
 *///from   w  w  w  .j  a v  a 2 s  .  c om
@Override
public void doSaveAs() throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(this.getDefaultDirectoryForSaveAs());
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            localizationResources.getString("PNG_Image_Files"), "png");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        ChartUtils.saveChartAsPNG(new File(filename), getChart(), getWidth(), getHeight(),
                getChartRenderingInfo());
    }
}

From source file:graph.plotter.LineGraph.java

/**
 * This method works for choosing file path
            /*w w  w .j  av a 2 s . c  o m*/
    */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    JFileChooser jf = new JFileChooser();
    jf.setBackground(Color.white);
    jf.showOpenDialog(null);
    File file = jf.getSelectedFile();
    String f = file.getAbsolutePath();
    jTextField4.setText(f);
}

From source file:VentanaPrincipal.java

private void descargarFichero() throws IOException {
    String directorio = lblRuta.getText();
    cliente.changeWorkingDirectory(directorio);
    JFileChooser chooser = new JFileChooser();
    cliente.enterLocalPassiveMode();//from www  . j a v a 2 s  . c o m
    cliente.setFileType(FTP.BINARY_FILE_TYPE);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(chooser.getSelectedFile().getAbsolutePath() + "/" + listFicheros
                        .getSelectedItem().substring(0, listFicheros.getSelectedItem().lastIndexOf("-"))));
        if (cliente.retrieveFile(
                listFicheros.getSelectedItem().substring(0, listFicheros.getSelectedItem().lastIndexOf("-")),
                out))
            lblMens.setText("Descargado correctamente ");
        else
            lblMens.setText("No se ha podido descargar");
        out.close();
    }
}

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;/*from  w  ww . jav  a 2  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:com.mycompany.zad1.MainWindow.java

private void chooseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseButtonActionPerformed
    JFileChooser chooser = new JFileChooser();
    int dialogResult = chooser.showOpenDialog(this);
    if (dialogResult == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();

        try {//from   w  w w.ja  v  a  2  s  . co  m
            imageOrginal = new ImageInOut().readImageFromFile(file);
            imageBuff = new ImageInOut().readImageFromFile(file);
        } catch (Exception ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    if (imageOrginal != null) {
        //            imageBuff = new ImageModel(imageOrginal);

        //            try {
        //                imageBuff = (ImageModel) imageOrginal.clone();
        //            } catch (CloneNotSupportedException ex) {
        //                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        //            }

        imageOrginalLabel.setIcon(new ImageIcon(imageOrginal.getImage()));
        imageMoiffayLabel.setIcon(new ImageIcon(imageBuff.getImage()));

        addBrightnessButton.setEnabled(true);
        addContrastButton.setEnabled(true);
        minusBrightnessButton.setEnabled(true);
        minusContrastButton.setEnabled(true);
        reverseColorButton.setEnabled(true);
        saveButton.setEnabled(true);
        laplasjanButton.setEnabled(true);
        kirshButton.setEnabled(true);
        averegeilterButton.setEnabled(true);
        medianFilterButton.setEnabled(true);
        calculateHistogramButton.setEnabled(true);
        histogramModifyButton.setEnabled(false);
        fourierButton.setEnabled(true);
        regionGrowingButton.setEnabled(true);

    }
}

From source file:de.ist.clonto.Ontogui.java

private void loadOntology(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_loadOntology
    if (null != dataset) {
        dataset.end();/*from   w  ww  .  ja v a  2  s  . c om*/
    }
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        dataset = TDBFactory.createDataset(fc.getSelectedFile().toString());
        ontologyNameField.setText(fc.getSelectedFile().getName());
        ontoPath = fc.getSelectedFile().toPath();
    } else {
        JOptionPane.showMessageDialog(this, "Loading ontology failed");
    }
}

From source file:dotaSoundEditor.Controls.ItemPanel.java

@Override
protected File promptUserForNewFile(String wavePath) {
    DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
    String waveString = selectedTreeNode.getUserObject().toString();
    String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", "");

    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav")
            : new FileNameExtensionFilter("MP3s", "mp3");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);/*  www  .j  a v  a 2s  . c  o m*/
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());

        int startIndex = -1;
        int endIndex = -1;
        //Get the actual value for the wavestring key-value pair.
        if (waveString.contains("\"wave\"")) {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3);
        } else //Some wavestrings don't have the "wave" at the beginning for some reason
        {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1);
        }
        String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
        String waveStringNormalizedFilePath = waveStringFilePath.substring(0,
                waveStringFilePath.lastIndexOf("\""));
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", "");
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", "");

        Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            if (waveString.contains("//")) {
                waveString = waveString
                        .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), "");
            }
            waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath
                    + "\" //Replaced by: " + chosenFile.getFileName().toString());
            selectedTreeNode.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

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

private void nuevaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevaActionPerformed
    try {/* w  ww  .  jav  a 2 s  .  c  om*/
        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);
    }
}