Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:duthientan.mmanm.com.Main.java

private void BntOpenKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntOpenKeyActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        if (isRSA) {
            key = selectedFile.getParent();
            JLKey.setText(selectedFile.getName());
            JFrame frame = new JFrame("ERROR");
            JOptionPane.showMessageDialog(frame, key);
            return;
        }/* w ww  .j  av a2s .c  o  m*/
        if (selectedFile.getName().contains(".txt")) {
            JLKey.setText(selectedFile.getName());
            try {
                BufferedReader br = new BufferedReader(new FileReader(selectedFile.getPath()));
                StringBuilder sb = new StringBuilder();
                String line = br.readLine();

                while (line != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                    line = br.readLine();
                }
                key = sb.toString();
                JFrame frame = new JFrame("ERROR");
                JOptionPane.showMessageDialog(frame, key);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JFrame frame = new JFrame("ERROR");
            JOptionPane.showMessageDialog(frame, "Please Choice File TXT");
        }
    }
}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void ButtonRapportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonRapportActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    String pattern = null;/*from ww w . jav  a 2 s .  co m*/
    String path;
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JASPER files", "jasper");
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(this);
    chooser.setMultiSelectionEnabled(false);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        pattern = chooser.getSelectedFile().getPath();
    }
    FileNameExtensionFilter filterpath = new FileNameExtensionFilter("PDF files", "pdf");
    JFileChooser chooserpath = new JFileChooser();
    chooserpath.setFileFilter(filterpath);
    int returnSave = chooserpath.showSaveDialog(this);
    if (returnSave == JFileChooser.APPROVE_OPTION) {
        path = chooserpath.getSelectedFile().getPath();

        if (!path.contains("pdf")) {
            path = path + ".pdf";
            String a = "\\";
        }
        pattern = pattern.replace("\\", "\\" + "\\");
        path = path.replace("\\", "\\" + "\\");

        ReportCreator creator = new ReportCreator();
        int a = creator.CreateReportDeal(pattern, idd, path);
        if (a == 1) {
            File file = new File(path.toString());
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException ex) {
                Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.intuit.tank.tools.script.ScriptFilterRunner.java

/**
 * @return/*  w w w . j  a  va2  s .c o  m*/
 */
private Component createTopPanel() {
    JPanel topPanel = new JPanel(new GridBagLayout());
    List<ConfiguredLanguage> configuredLanguages = ConfiguredLanguage.getConfiguredLanguages();
    languageSelector = new JComboBox(configuredLanguages.toArray());
    languageSelector.setSelectedIndex(0);
    languageSelector.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            setSyntaxStyle();
        }
    });

    currentFileLabel = new JLabel();

    final JFileChooser jFileChooser = new JFileChooser();
    jFileChooser.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "Tank XML Files";
        }

        @Override
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase().endsWith("_ts.xml");
        }
    });

    JButton button = new JButton("Select File...");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            int showOpenDialog = jFileChooser.showOpenDialog(ScriptFilterRunner.this);
            if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
                loadTSXml(jFileChooser.getSelectedFile());
            }
        }

    });
    xmlViewDialog = new XMlViewDialog(this);
    xmlViewDialog.setSize(new Dimension(800, 500));
    showXmlBT = new JButton("Show XML");
    showXmlBT.setEnabled(false);
    showXmlBT.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            displayXml();
        }

    });

    saveBT = new JButton("Save XML");
    saveBT.setEnabled(false);
    saveBT.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            saveXml();
        }

    });

    JPanel xmlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 10, 20));
    xmlPanel.add(button);
    xmlPanel.add(showXmlBT);
    xmlPanel.add(saveBT);

    int y = 0;

    topPanel.add(new JLabel("Current Tank XML: "), getConstraints(0, y, GridBagConstraints.NONE));
    topPanel.add(currentFileLabel, getConstraints(1, y++, GridBagConstraints.HORIZONTAL));

    topPanel.add(new JLabel("Select Script Language: "), getConstraints(0, y, GridBagConstraints.NONE));
    topPanel.add(languageSelector, getConstraints(1, y++, GridBagConstraints.HORIZONTAL));

    topPanel.add(new JLabel("Select Tank XML: "), getConstraints(0, y, GridBagConstraints.NONE));
    topPanel.add(xmlPanel, getConstraints(1, y++, GridBagConstraints.HORIZONTAL));
    return topPanel;
}

From source file:net.sf.jclal.gui.view.components.chart.ExternalBasicChart.java

/**
 *
 * @return Create the menu that allows load the result from others
 * experiments.//from  w ww. j  a  v a2 s .c  om
 */
private JMenu createMenu() {

    final JMenu fileMenu = new JMenu("Options");

    final JFileChooser f = new JFileChooser();
    f.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    fileMenu.add("Add report file or directory").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (curveOptions != null) {
                curveOptions.setVisible(false);
                curveOptions = null;
            }
            int action = f.showOpenDialog(fileMenu);

            if (action == JFileChooser.APPROVE_OPTION) {

                loadReportFile(f.getSelectedFile());

            }

        }
    });

    fileMenu.add("Area under learning curve (ALC)").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            if (comboBox.getItemCount() != 0) {

                if (!comboBox.getSelectedItem().toString().isEmpty()) {

                    StringBuilder st = new StringBuilder();

                    st.append("Measure: ").append(comboBox.getSelectedItem()).append("\n\n");

                    for (int query = 0; query < queryNames.size(); query++) {

                        double value = LearningCurveUtility.getArea(evaluationsCollection.get(query),
                                comboBox.getSelectedItem().toString());

                        String valueString = String.format("%.3f", value);

                        st.append(queryNames.get(query)).append(": ").append(valueString).append("\n");

                    }

                    JOptionPane.showMessageDialog(content, st.toString(), "Area under the learning curve",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }
    });

    fileMenu.add("Clear").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            queryNames = new ArrayList<String>();
            evaluationsCollection = new ArrayList<List<AbstractEvaluation>>();
            comboBox.removeAllItems();
            controlCurveColor = new HashMap<String, Color>();
            colors.clear();
            data = null;
            set.clear();
            curveOptions.setVisible(false);
            curveOptions = null;
            setSeries.clear();
            passiveEvaluation = null;

        }
    });

    fileMenu.add("Curve options").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            data = informationTable();

            if (queryNames.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Please add curves");
                return;
            }
            if (curveOptions == null) {
                curveOptions = new LearningCurvesVisualTable(ExternalBasicChart.this);
            } else {
                curveOptions.setVisible(true);
            }

        }

    });

    final JCheckBox viewPoints = new JCheckBox("View points's shapes");
    viewPoints.setSelected(false);

    viewPoints.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            viewPointsForm = viewPoints.isSelected();
            jComboBoxItemStateChanged();
        }
    });

    fileMenu.add(viewPoints);

    final JCheckBox withOutColor = new JCheckBox("View without color");
    withOutColor.setSelected(false);

    withOutColor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            viewWithOutColor = withOutColor.isSelected();
            jComboBoxItemStateChanged();
        }
    });

    fileMenu.add(withOutColor);

    return fileMenu;
}

From source file:com._17od.upm.gui.DatabaseActions.java

public void openDatabase() throws IOException, ProblemReadingDatabaseFile, CryptoException {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(Translator.translate("openDatabase"));
    int returnVal = fc.showOpenDialog(mainWindow);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File databaseFile = fc.getSelectedFile();
        if (databaseFile.exists()) {
            openDatabase(databaseFile.getAbsolutePath());
        } else {/*from  www.j a  v a  2  s  . c o  m*/
            JOptionPane.showMessageDialog(mainWindow,
                    Translator.translate("fileDoesntExistWithName", databaseFile.getAbsolutePath()),
                    Translator.translate("fileDoesntExist"), JOptionPane.ERROR_MESSAGE);
        }
    }

    // Stop any "SetDBDirtyThread"s that are running
    runSetDBDirtyThread = false;
}

From source file:duthientan.mmanm.com.Main.java

private void BntOpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntOpenFileActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);
    int returnValue = fileChooser.showOpenDialog(null);

    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File[] selectedFiles = fileChooser.getSelectedFiles();
        JLFILEPATH.setText(selectedFiles.length + " files is selected");
        JLMD5.setText("Caculating");
        filePath = new ArrayList<>();
        new Thread(new Runnable() {
            @Override// www .ja v a  2s  .c o  m
            public void run() {
                try {
                    String mD5 = "";
                    for (File f : selectedFiles) {
                        filePath.add(f.getPath());
                        FileInputStream fis = new FileInputStream(f);
                        mD5 += f.getName() + " : " + org.apache.commons.codec.digest.DigestUtils.md5Hex(fis)
                                + "<br>";
                        fis.close();
                    }
                    JLMD5.setText("<html>" + mD5 + "</html>");
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    }
}

From source file:au.org.ala.delta.editor.DeltaEditor.java

public File selectFile(boolean open) {
    File selectedFile = null;//from  www. j a  va  2 s.c o m
    JFileChooser chooser = new JFileChooser();

    if (_lastDirectory != null) {
        chooser.setCurrentDirectory(_lastDirectory);
    }

    chooser.setFileFilter(new FileNameExtensionFilter("Delta Editor files *.dlt", DELTA_FILE_EXTENSION));
    int dialogResult;
    if (open) {
        dialogResult = chooser.showOpenDialog(getMainFrame());
    } else {
        dialogResult = chooser.showSaveDialog(getMainFrame());
    }
    if (dialogResult == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        _lastDirectory = chooser.getCurrentDirectory();
    }
    return selectedFile;
}

From source file:edu.harvard.mcz.imagecapture.jobs.JobCleanDirectory.java

private List<File> getFileList() {
    ArrayList<File> files = new ArrayList<File>();
    String pathToCheck = "";
    // Find the path in which to include files.
    File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
    File startPoint = null;/* w w  w .j  a  v  a 2 s. c om*/
    // If it isn't null, retrieve the image base directory from properties, and test for read access.
    if (Singleton.getSingletonInstance().getProperties().getProperties()
            .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                "Can't start scan.  Don't know where images are stored.  Set imagbase property.", "Can't Scan.",
                JOptionPane.ERROR_MESSAGE);
    } else {
        imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
        if (imagebase != null) {
            if (imagebase.canRead()) {
                startPoint = imagebase;
            } else {
                // If it can't be read, null out imagebase
                imagebase = null;
            }
        }
        if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
            // A scan start point has been provided, don't launch a dialog.
            startPoint = startPointSpecific;
        }
        if (imagebase == null || scan == SCAN_SELECT) {
            // launch a file chooser dialog to select the directory to scan
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                fileChooser.setCurrentDirectory(startPointSpecific);
            } else {
                if (Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                    fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                            .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                }
            }
            int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                log.debug("Selected base directory: " + file.getName() + ".");
                startPoint = file;
            } else {
                //TODO: handle error condition
                log.error("Directory selection cancelled by user.");
            }
        }

        // Check that startPoint is or is within imagebase.
        if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
            String base = Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
            log.error("Tried to scan directory (" + startPoint.getPath() + ") outside of base image directory ("
                    + base + ")");
            String message = "Can't scan and cleanup files outside of base image directory (" + base + ")";
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
        } else if (ImageCaptureProperties.getPathBelowBase(startPoint).trim().length() == 0) {
            String base = Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
            log.error("Tried to scan directory (" + startPoint.getPath()
                    + ") which is the base image directory.");
            String message = "Can only scan and cleanup files in a selected directory within the base directory  ("
                    + base + ").\nYou must select some subdirectory within the base directory to cleanup.";
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Can't Cleanup image base directory.", JOptionPane.YES_NO_OPTION);

        } else {
            if (!startPoint.canRead()) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                        "Can't Scan.", JOptionPane.YES_NO_OPTION);
            } else {
                pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);

                // retrieve a list of image records in the selected directory
                ICImageLifeCycle ils = new ICImageLifeCycle();
                List<ICImage> images = ils.findAllInDir(pathToCheck);
                Iterator<ICImage> iter = images.iterator();
                while (iter.hasNext()) {
                    ICImage image = iter.next();
                    File imageFile = new File(
                            ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));
                    files.add(imageFile);
                    counter.incrementFilesSeen();
                }

            }
        }
    }

    log.debug("Found " + files.size() + " Image files in directory to check.");

    return files;
}

From source file:com.sshtools.common.ui.SshToolsApplicationClientPanel.java

/**
 *
 *//*w  ww.ja v a2s .  c  om*/
public void editConnection() {
    // Create a file chooser with the current directory set to the
    // application home
    JFileChooser fileDialog = new JFileChooser(PreferencesStore.get(PREF_CONNECTION_FILE_DIRECTORY,
            System.getProperty("sshtools.home", System.getProperty("user.home"))));
    fileDialog.setFileFilter(connectionFileFilter);

    // Show it
    int ret = fileDialog.showOpenDialog(this);

    // If we've approved the selection then process
    if (ret == fileDialog.APPROVE_OPTION) {
        PreferencesStore.put(PREF_CONNECTION_FILE_DIRECTORY,
                fileDialog.getCurrentDirectory().getAbsolutePath());

        // Get the file
        File f = fileDialog.getSelectedFile();

        // Load the profile
        SshToolsConnectionProfile p = new SshToolsConnectionProfile();

        try {
            p.open(f);

            if (editConnection(p)) {
                saveConnection(false, f, p);
            }
        } catch (IOException ioe) {
            showErrorMessage(this, "Failed to load connection profile.", "Error", ioe);
        }
    }
}

From source file:com._17od.upm.gui.DatabaseActions.java

public void importAccounts() throws TransportException, ProblemReadingDatabaseFile, IOException,
        CryptoException, PasswordDatabaseException {
    if (getLatestVersionOfDatabase()) {
        // Prompt for the file to import
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle(Translator.translate("import"));
        int returnVal = fc.showOpenDialog(mainWindow);

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

            // Unmarshall the accounts from the CSV file
            try {
                AccountsCSVMarshaller marshaller = new AccountsCSVMarshaller();
                ArrayList accountsInCSVFile = marshaller.unmarshal(csvFile);
                ArrayList accountsToImport = new ArrayList();

                boolean importCancelled = false;
                // Add each account to the open database. If the account
                // already exits the prompt to overwrite
                for (int i = 0; i < accountsInCSVFile.size(); i++) {
                    AccountInformation importedAccount = (AccountInformation) accountsInCSVFile.get(i);
                    if (database.getAccount(importedAccount.getAccountName()) != null) {
                        Object[] options = { "Overwrite Existing", "Keep Existing", "Cancel" };
                        int answer = JOptionPane.showOptionDialog(mainWindow,
                                Translator.translate("importExistingQuestion",
                                        importedAccount.getAccountName()),
                                Translator.translate("importExistingTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

                        if (answer == 1) {
                            continue; // If keep existing then continue to the next iteration
                        } else if (answer == 2) {
                            importCancelled = true;
                            break; // Cancel the import
                        }/* w w  w  . j a  v a2s .  c o m*/
                    }

                    accountsToImport.add(importedAccount);
                }

                if (!importCancelled && accountsToImport.size() > 0) {
                    for (int i = 0; i < accountsToImport.size(); i++) {
                        AccountInformation accountToImport = (AccountInformation) accountsToImport.get(i);
                        database.deleteAccount(accountToImport.getAccountName());
                        database.addAccount(accountToImport);
                    }
                    saveDatabase();
                    accountNames = getAccountNames();
                    filter();
                }

            } catch (ImportException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            } catch (CryptoException e) {
                JOptionPane.showMessageDialog(mainWindow, e.getMessage(),
                        Translator.translate("problemImporting"), JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}